来自data.table d
,例如
require(data.table)
d = data.table(a = 1:4, b = 11:14, c = 21:24, group = c(1,1,2,2))
我想通过varsToSum
的唯一值将所有名称存储在向量group
中的变量加起来。
varsToSum = c("a", "b")
对于上述d
和varsToSum
,预期结果为
d[,list(a = sum(a), b = sum(b)),list(group)]
group a b
1: 1 3 23
2: 2 7 27
相关帖子:
答案 0 :(得分:4)
d[, lapply(.SD, sum), by = group, .SDcols = varsToSum]
group a b
1: 1 3 23
2: 2 7 27