R:从目标列中减去可变数量的列

R: subtract variable amount of columns from target column

我希望创建一个接受三个参数的函数:一个 data.table、一个目标列和一个要从目标列中减去的列向量:

test = data.table(
  total = c(10,6,4,4,5,6), 
  b = c(9,5,3,3,4,5), 
  c = rep(1, 6),
  d = rep(2, 6)
)

函数(数据,目标="total",cols=c("b","c")) 应该给出所需的输出:

test = data.table(
  total = c(10,6,4,4,5,6), 
  b = c(9,5,3,3,4,5), 
  c = rep(1, 6),
  d = rep(2, 6),
  new_total = rep(0, 6)
)

目前的尝试次数:

1)

testfunction <- function(dt, target, cols){
    dt[, new_total := target - .SD , .SDcols = cols]

}

2)

testfunction <- function(dt, target, cols){
     temp = copy(dt[, .SD, .SDcols = cols])
     dt[, new_total := target - temp]

 }

None 的这些工作,不幸的是,我认为我的尝试表明缺乏对 data.table 的理解。

试试这个:

foo <- function(data, target = "total", cols = c("b", "c")) {
  data[, new_total := get(target) - rowSums(.SD), .SDcols = cols]
}

foo(test)[]

#    total b c d new_total
# 1:    10 9 1 2         0
# 2:     6 5 1 2         0
# 3:     4 3 1 2         0
# 4:     4 3 1 2         0
# 5:     5 4 1 2         0
# 6:     6 5 1 2         0

问题是

  1. .SD 是一个 data.tabletarget 只是一个向量。

  2. 要获取带有字符串变量的列不能这样完成,例如,您可以使用 get()。更多示例 .