When creating a new variable with columns, data.table does not allow quoted column names. This yields the following problem when using a data.table within a function.
library(data.table)
dt <- data.table(var1 = c(1:10), var2 = seq(2,20,2), var3 = seq(40,4,-4))
addColumnsError <- function(dt, v1, v2){
dt[,v1 + v2]
}
addColumnsError(dt, var1, var2)
> Error in eval(jsub, SDenv, parent.frame()) : object 'var1' not found
addColumnsError(dt, "var1", "var2")
> Error in v1 + v2 : non-numeric argument to binary operator
The following workaround handles this problem.
addColumns <- function(dt,v1,v2){
v1<-as.character(substitute(v1))
v2<-as.character(substitute(v2))
dt[,eval(parse(text=v1)) + eval(parse(text=v2))]
}
addColumns(dt, var1, var2)
[1] 3 6 9 12 15 18 21 24 27 30
addColumns(dt, "var1", "var2")
[1] 3 6 9 12 15 18 21 24 27 30
Is there a more elegant way to pass column names to a data.table object within a function?
(Note: I could just call the data.table function but I intend to make more complicated calculations :) )