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

前端 未结 2 998
旧时难觅i
旧时难觅i 2020-12-11 03:07

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 s

相关标签:
2条回答
  • 2020-12-11 03:41

    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))
    
    0 讨论(0)
  • 2020-12-11 03:55

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

    abc12-3def
    

    at the R prompt, it would throw a syntax error, so too will parse. You can't just throw arbitrary text at it and assume it'll give you something sensible.

    0 讨论(0)
提交回复
热议问题