This question is related to R - pass fixed columns to lapply function in data.table and weighted means by group and column, but somewhat different.
I would like to have one fixed column interacting with all other columns in a data.table
. A trivial example to illustrate:
DT <- data.table(y = rnorm(10), x1 = rnorm(10), x2 = rnorm(10))
DT[, lapply(c('x1', 'x2'), function(x) get(x) * y)]
Now suppose that the operation is a lot more complicated than multiplication, such that I would like to define a standalone function outside the scope of the data.table
:
fun <- function(x) {
return(get(x) * y)
}
DT[, lapply(c('x1', 'x2'), fun)]
Error in get(x) : object 'x1' not found
Obvious there is an issue with variable scope, since the function defined outside the data.table
cannot see the variables inside. Is there any clever trick to define the function outside data.table
and still be able to use lapply
?