C8H*_*4O2 5 evaluation r arithmetic-expressions
我想评估一个包含算术表达式的字符串向量 - "1 + 2","5*6"等.
我知道我可以将单个字符串解析为表达式,然后将其评估为eval(parse(text="1+2")).
但是,我更愿意在不使用for循环的情况下评估向量.
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
Run Code Online (Sandbox Code Playgroud)
只需应用整个功能.
sapply(foo, function(x) eval(parse(text=x)))
Run Code Online (Sandbox Code Playgroud)