我有以下功能:
DT <- data.table(col1 = 1:4, col2 = c(2:5))
fun <- function(DT, fct){
DT_out <- DT[,new_col := fct]
return(DT_out)
}
fun(input, fct = function(x = col1, y = col2){y - x})
事实上,我在这个代码片段之前和之后都有一些处理,因此我不希望直接将语句DT[,new_col := fct]
与固定的fct
一起使用(因为fct
应该是灵活的(。我知道这个问题与这个问题非常相似,但我不知道如何重新制定代码,以便允许两列作为函数的参数。上面的代码给出了错误:
Error in `[.data.table`(DT, , `:=`(new_col, fct)) :
RHS of assignment is not NULL, not an an atomic vector (see ?is.atomic) and not a list column.
如果您不介意在变量名周围添加引号,请选择一个选项
fun <- function(DT, fun, ...){
fun_args <- c(...)
DT[,new_col := do.call(fun, setNames(mget(fun_args), names(fun_args)))]
}
fun(DT, fun = function(x, y){y - x}, x = 'col1', y = 'col2')
DT
# col1 col2 new_col
# 1: 1 2 1
# 2: 2 3 1
# 3: 3 4 1
# 4: 4 5 1
或使用.SDcols
(与上述结果相同(
fun <- function(DT, fun, ...){
fun_args <- c(...)
DT[, new_col := do.call(fun, setNames(.SD, names(fun_args))),
.SDcols = fun_args]
}