【问题标题】:Function in data.table with two columns as argumentsdata.table 中的函数,具有两列作为参数
【发布时间】:2020-07-01 19:26:56
【问题描述】:

我有以下功能:

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})

实际上我在这段代码sn-p之前和之后都有一些处理,因此我不希望直接使用带有固定fct的语句DT[,new_col := fct](因为fct应该是灵活的)。我知道这个问题与this 非常相似,但我无法弄清楚如何重新编写代码,以便允许将两列作为函数的参数。上面的代码给出了错误:

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. 

【问题讨论】:

  • 你想要new_col := fct(col1,col2)吗?实际上,您正在为 new_col 分配一个函数,而不是它的输出
  • 不,这不能满足我的需求,因为我希望参数像下面给出的答案一样灵活!不过还是谢谢

标签: r function input data.table multiple-columns


【解决方案1】:

如果您不介意在变量名周围添加引号,则可以选择一个

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]
}

【讨论】:

  • 是的!两者都是不错的解决方案,但我更喜欢.SDcols 的第二个解决方案。在我看来,它更清晰,更符合data.table 的风格。非常感谢您指出三点结构,这为我打开了一个全新的世界!
猜你喜欢
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
  • 2012-02-29
  • 1970-01-01
  • 2015-08-23
  • 1970-01-01
  • 1970-01-01
  • 2014-10-15
相关资源
最近更新 更多