This question is the data.table equivalent of Pass a data.frame column name to a function.
Suppose I have a very simple data.table:
dat <- data.table(x = 1:4,
y = 5:8)
Now I want to create a new column for any given function:
new_column <- function(df,col_name,expr){
col_name <- deparse(substitute(col_name))
df[[col_name]] <- eval(substitute(expr),df,parent.frame())
df
}
So that it correctly provides:
> new_column (dat,z,x+y)
x y z
1 1 5 6
2 2 6 8
3 3 7 10
4 4 8 12
However , because it is a data.table I would like to create this new column using :=
:
new_column_byref <- function(df,col_name,expr){
col_name <- deparse(substitute(col_name))
df[, col_name:=eval(substitute(expr)
,df
,parent.frame()
)]
df
}
But it does not work:
> a <- new_column_byref(dat,z,x+y)
Error: Check that is.data.table(DT) == TRUE. Otherwise, :=, `:=`(...) and let(...) are defined for use in j, once only and in particular ways. See help(":=").
How do I fix this? Thank you.