In R, evaluate expressions within vector of strings

后端 未结 2 1126
夕颜
夕颜 2020-12-09 13:17

I wish to evaluate a vector of strings containing arithmetic expressions -- \"1+2\", \"5*6\", etc.

I know that I can parse a single string into an expression and t

相关标签:
2条回答
  • 2020-12-09 13:53

    Just to show that you can also do this with a for loop:

    result <- numeric(length(foo))
    foo <- parse(text=foo)
    for(i in seq_along(foo))
        result[i] <- eval(foo[[i]])
    

    I'm not a fan of using the *apply functions for their own sake, but in this case, sapply really does lead to simpler, clearer code.

    0 讨论(0)
  • 2020-12-09 14:11

    Just apply the whole function.

    sapply(foo, function(x) eval(parse(text=x)))
    
    0 讨论(0)
提交回复
热议问题