Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected symbol error in parse(text = str) with hyphen after a digit

Tags:

parsing

r

I am trying to parse a character string in R. R throws an "unexpected symbol" or "unexpected end of input" exception when there is a digit followed by a hyphen in the string (please see the code). Searching and trying different ways to solve this issue didn't help. Probably some lack of knowledge in my part. Any help or advise would be highly appreciated.

> str <- "abc12-3def"
> parse(text = str)
Error in parse(text = str) : <text>:1:8: unexpected symbol
1: abc12-3def
          ^

or

> str <- "abc123-"
> parse(text = str)
Error in parse(text = str) : <text>:2:0: unexpected end of input
1: abc123-
  ^

However, following examples all work normally

> str <- "abc123def"
> parse(text = str)
expression(abc123def)

or

> str <- "abc123-def"
> parse(text = str)
expression(abc123-def)

or

> str <- "abc12-3"
> parse(text = str)
expression(abc12-3)

Thank you very much in advance!

like image 841
Dzah Avatar asked Jul 14 '13 12:07

Dzah


People also ask

What does unexpected symbol mean in R?

These errors mean that the R code you are trying to run or source is not syntactically correct. That is, you have a typo. To fix the problem, read the error message carefully. The code provided in the error message shows where R thinks that the problem is. Find that line in your original code, and look for the typo.

What is error in parse in R?

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.

What does error unexpected '>' in Mean in R studio?

The RStudio console returned the error message “unexpected '}' in X”. The reason for this is that we used one curly bracket too much at the end of our code. This can easily happen when if else statements or in user-defined functions are getting more complex.


Video Answer


1 Answers

You can easily reproduce the parse behavior with :

str <- "3a"
parse(text = str)

parse try to parse your str as a variable name. Or, you should give an available variable name, either it should not begin with a digit or you should put it between ``. the following works :

str <- "`3a`"
parse(text = str)

and in your example , this works also :

str <- "abc12-`3def`"
parse(text = str)

Finally for your second example , it is logic that it will not work since you don't give an available expression to parse:

str <- "abc123-"  ## this will like myvar-

if your - is just a string separator, why not to transform it to _? for example:

 parse(text=gsub('-','_',str))
like image 178
agstudy Avatar answered Sep 21 '22 05:09

agstudy