I wish to make a function that takes in three arguments: a data.table, a target column and a vector of columns to subtract from the target column:
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)
)
function(data, target = "total", cols = c("b", "c")) should give desired output:
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)
)
Attempts so far:
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 of these work, and I think my attempt show a lack of understanding of data.table, unfortunately.