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
sapply
is vectorizing? – Snowcladsapply
is the same thing asfor
loop, just slower. For such simple operation, afor
loop will be a better choice. InR
, this is not what you mean by saying "vectorized solution" – Snowcladsapply
:for(i in seq_along(foo)){ eval(parse(text = foo[i])) }
– Snowcladsapply
to anything neither, but you could addprint
there or something. Anyhow, I think I made my point clear so we can close this – Snowcladsapply
is returning a value, the intended value in a vector. Your loop doesn't. – Nichromeprint
– Snowcladprint
doesn't return a value. It just prints the values. You would need to make your loop assign the values to a vector to match the effect and have it act as a solution to the question. No one wants their values printed to the screen. They want them in an object so they can use them. What your for loop does is calculate the result and leave it be. – Nichromesapply
? As it stands, it is only printing the output to the screen – Snowcladsapply
returns a vector? – Nichromefoo <- sapply(foo, function(x) eval(parse(text=x)))
will be very slightly more efficient thanfor(i in seq_along(foo)) foo[i] <- eval(parse(text = foo[i]))
, but I don't think this is the case here and it still won't be a vecorized solution – Snowcladsapply
is not abstracting away the loop, it is just hiding it – SnowcladrowSums
or such. – Snowclad