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

I am trying to parse a character string in R. R throws an exception “unexpected character” or “unexpected end of input” if there is a digit in the string and then a hyphen (see Code). Search and attempts to solve this problem in different ways did not help. Perhaps some flaws in my part. Any help or recommendations would be greatly 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, the following examples work fine

 > 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 in advance!

+4
source share
2 answers

You can easily reproduce the parse behavior with:

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

parse try to parse your str as a variable name. Either you must indicate the available variable name, either it should not start with a digit, or you must put it between ``. following works:

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

and in your example, this also works:

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

Finally, for your second example, it is logical that it will not work, since you are not giving an accessible expression for parsing:

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

if yours is just a line separator, why not convert it to _ ? eg:

  parse(text=gsub('-','_',str)) 
+3
source

The point of parse is to turn your input into an R-language expression. As if you typed

 abc12-3def 

in the hint of R, this will result in a syntax error, so there will also be parse . You cannot simply throw arbitrary text on it and assume that it will give you something reasonable.

+1
source

Source: https://habr.com/ru/post/1491314/


All Articles