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?
c(2,4,6)
CodePudding user response:
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
CodePudding user response:
Purrr is your friend.
library(purrr)
equations <- c("1 1","2 2","3 3")
map_dbl(.x = equations, .f = function(equation){
eval(parse(text = equation))
})
[1] 2 4 6