In R, evaluate expressions within vector of strings

偶尔善良 提交于 2019-12-03 19:36:43

问题


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 then evaluate it as in eval(parse(text="1+2")).

However, I would prefer to evaluate the vector without using a for loop.

foo <- c("1+2","3+4","5*6","7/8") # I want to evaluate this and return c(3,7,30,0.875)
eval(parse(text=foo[1])) # correctly returns 3, so how do I vectorize the evaluation?
eval(sapply(foo, function(x) parse(text=x))) # wrong! evaluates only last element

回答1:


Just apply the whole function.

sapply(foo, function(x) eval(parse(text=x)))



回答2:


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.



来源:https://stackoverflow.com/questions/24975229/in-r-evaluate-expressions-within-vector-of-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!