这个问题就是数据.表相当于Pass a data.frame column name to a function.
假设我有一个非常简单的数据.表:
dat <- data.table(x = 1:4,
y = 5:8)
现在我想为任何给定函数创建一个新列:
new_column <- function(df,col_name,expr){
col_name <- deparse(substitute(col_name))
df[[col_name]] <- eval(substitute(expr),df,parent.frame())
df
}
从而正确地提供:
> 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
然而,因为这是一个数据.表I希望使用:=
创建此新列:
new_column_byref <- function(df,col_name,expr){
col_name <- deparse(substitute(col_name))
df[, col_name:=eval(substitute(expr)
,df
,parent.frame()
)]
df
}
但它不起作用:
> 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(":=").
我该怎么解决这个问题?非常感谢.