本文介绍了在R中,计算字符串向量中的表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望评估一个包含算术表达式-"1 + 2","5 * 6"等的字符串向量
I wish to evaluate a vector of strings containing arithmetic expressions -- "1+2", "5*6", etc.
我知道我可以将单个字符串解析为一个表达式,然后像eval(parse(text="1+2"))
中那样对其求值.
I know that I can parse a single string into an expression and then evaluate it as in eval(parse(text="1+2"))
.
但是,我宁愿不使用for循环来评估向量.
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
推荐答案
只需应用整个功能.
sapply(foo, function(x) eval(parse(text=x)))
这篇关于在R中,计算字符串向量中的表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!