2

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)

2 Answers2

3

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
akrun
  • 874,273
  • 37
  • 540
  • 662
  • `unname(` approach is immune to ++-, is there an approach to achieve the same with `rowSums(read.table`? i.e. there are two sep(s). – Chris Dec 29 '22 at 05:39
  • I think the constraint is `read.table` rather than rowSums, and I'm trying to estimate if you get to 1mil before r questions get to 510K. Putting thumb on scale... – Chris Dec 29 '22 at 05:43
  • I meant if the expression is `c("1*2", "1+ 3 *5^2")` etc, rowSums wouldn't work. – akrun Dec 29 '22 at 05:46
  • which still works for `unname(sapply(` case so rowSums(read.table is really a more restrictive edge case, that is good to know. – Chris Dec 29 '22 at 05:50
2

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