Let's say I have the following data.table
and would like to get the output below by referring to variables stored in a vector:
dt <- data.table(a = rep(1, 3),
b = rep(2, 3))
x <- 'a'
y <- 'b'
dt[, .(sum(get(x)), mean(get(y)))]
V1 V2
1: 3 2
Cool, it works. But now I'd like to make a function, and then do something like:
foo <- function(arg1, arg2) {
dt[, .(sum(get(arg1)), mean(get(arg2)))]
}
foo(x, y)
Realizing it works, I'd like to avoid calling all those gets
, and do something like:
foo <- function(arg1, arg2) {
eval(substitute(dt[, .(sum(arg1), mean(arg2))]))
}
foo(x, y) # or foo('x', 'y')
But this fails. Any idea on how to evaluate all the arguments at once in a way similar to calling get
multiple times?