Evaluate MULTIPLE equations writern in a character/string vector in R


As many of you have suggested, to evaluate an equation writing in a string or character, one can use eval(parse(text = "your equation")) as follows:

eval(parse(text = "1+1"))

This works very well when you have only one equation. But when you have a vector of equations written as strings/characters, it only evaluates the last equation:

eval(parse(text = c("1+1","2+2","3+3")))

How could one evaluate all these expressions and have the vector of results at the end?


>Solution :

It is not vectorized, i.e. it needs to be looped

unname(sapply(c("1+1","2+2","3+3"), function(x) eval(parse(text = x))))
[1] 2 4 6

If we know the operator, an option is also to either split up or use read.table to read as two columns and then use rowSums

rowSums(read.table(text = c("1+1","2+2","3+3"), header = FALSE, sep = "+"))
[1] 2 4 6

Leave a ReplyCancel reply