R,data.table:对名称存储在向量中的所有列求和

R, data.table: Sum all columns whose names are stored in a vector

来自 data.table d 例如

require(data.table)
d = data.table(a = 1:4, b = 11:14, c = 21:24, group = c(1,1,2,2))

我想通过 group.

的唯一值对名称存储在向量 varsToSum 中的所有变量求和
varsToSum = c("a", "b")

对于上述dvarsToSum,预期结果是

d[,list(a = sum(a), b = sum(b)),list(group)]

   group a  b
    1: 1 3 23
    2: 2 7 27

相关帖子:

d[, lapply(.SD, sum), by = group, .SDcols = varsToSum]

   group a  b
1:     1 3 23
2:     2 7 27