【发布时间】:2023-04-05 18:15:02
【问题描述】:
我希望创建一个接受三个参数的函数:一个 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]
}
这些都不起作用,不幸的是,我认为我的尝试表明缺乏对 data.table 的理解。
【问题讨论】:
标签: r data.table subtraction