mnosefish
mnosefish

Reputation: 379

Pass an expression as a function argument in R

I'm trying to write a function which will accept an expression consisting of one or more column names as in the below:

data <- data.frame(a = c(1 , 2 , 3) , b = c(1 , 2 , 3))
beans <- function (data , expr) {
    with(data , expr)
}

The desired output is something like:

beans(data , expression(a + b))
# [1] 2 4 6

but this instead returns

expression(a + b)

Ideally, a solution would allow a single column to be used as an argument as well, e.g.

beans(data , a)
# [1] 1 2 3

Upvotes: 1

Views: 924

Answers (1)

Zheyuan Li
Zheyuan Li

Reputation: 73395

You need to eval (even outside the function):

with(data, eval(expr))
eval(expr, envir = data)

Upvotes: 3

Related Questions