Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

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

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")))
6

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

c(2,4,6)

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading