Evaluate expression given as a string

前端 未结 7 1912
小蘑菇
小蘑菇 2020-11-21 23:41

I\'m curious to know if R can use its eval() function to perform calculations provided by e.g. a string.

This is a common case:

eval(\"5         


        
相关标签:
7条回答
  • 2020-11-22 00:19

    Not sure why no one has mentioned two Base R functions specifically to do this: str2lang() and str2expression(). These are variants of parse(), but seem to return the expression more cleanly:

    eval(str2lang("5+5"))
    
    # > 10
      
    eval(str2expression("5+5"))
    
    # > 10
    
    

    Also want to push back against the posters saying that anyone trying to do this is wrong. I'm reading in R expressions stored as text in a file and trying to evaluate them. These functions are perfect for this use case.

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