This error typically occurs if you have a string starting with a number or if a hyphen is in the wrong place.
To solve this error you can change the string so that it does not start with a number.
This tutorial will go through the error in detail and how to solve it with code examples.
Example
Let’s look at an example of a string, which we want to parse into an R expression:
str <- "xyz01-3lf" parse(text=str)
Error in parse(text = str) : <text>:1:8: unexpected symbol 1: xyz01-3lf ^
We raise the error because R interprets the hyphen as the arithmetic operator for subtraction. The R cannot evaluate this as an expression therefore we cannot prase the string to an expression.
Solution
We can solve this error by removing the hyphen from the string. Let’s look at the revised code:
str <- "xyz013lf" parse(text=str)
Let’s run the code to see the result:
expression(xyz013lf)
We can also substitute the hyphen for an underscore using gsub. Let’s look at the revised code:
parse(text=gsub('-', '_', str))
Let’s run the code to get the result:
expression(xyz01_3lf)
We can also put the string in backticks. Let’s look at the revised code:
str <- "xyz01-'3lf'" parse(text=str)
Let’s run the code to see the result:
expression(`xyz01-3lf`)
Example
Let’s look at another example of a string starting with a number:
str <- "4xx Error" parse(text=str)
Let’s run the code to see what happens:
Error in parse(text = str) : <text>:1:2: unexpected symbol 1: 4xx ^
The error occurs because the string starts with a number.
Solution
We can solve this error by wrapping the string in backticks. Let’s look at the revised code:
str <- "'4xx Error'" parse(text=str)
Let’s run the code to get the result:
expression('4xx Error')
Summary
Congratulations on reading to the end of this tutorial!
For further reading on R related errors, go to the articles:
- How to Solve R Error: plot.window(…): need finite ‘ylim’ values
- How to Solve R Error: non-numeric argument to binary operator
- How to Solve R Error model.frame.default: ‘data’ must be a data.frame, environment, or list
Go to the online courses page on R to learn more about coding in R for data science and machine learning.
Have fun and happy researching!
Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.