revaluationarithmetic-expressions

In R, evaluate expressions within vector of strings


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

Solution

  • I just came across the same problem, and with the need for speed. It resulted in the solution (function) below. The idea is that it is faster to evaluate a vector than to evaluate its elements. The use below is with the '%>%' syntax from the dplyr or magrittr packages.

    evaluate_string <- function(x) {
        parse(text = paste(
           paste(
            "c(",
            collapse = ""
           ),
           paste(paste(x, c(rep(",", length(x) - 1), ")"), sep = ""), collapse = " "),
        collapse = " "
    )) %>%
        eval() %>%
        return()}