Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

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

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...