跨列而不是行的累积总和

时间:2017-10-27 15:42:30

标签: r data.table cumsum

我有data.table dt,如下所示。

df <- data.frame(t1 = rep(0,5), t3 = c(12, 5, 8,9, 5), t7= c(25, 48, 7, 9, 14))
dt <- setDT(df)
dt
   t1 t3 t7
1:  0 12 25
2:  0  5 48
3:  0  8  7
4:  0  9  9
5:  0  5 14

我想获得各列的累积总和。我只是越过行。如何在data.table

中执行此操作
dt[, 1:3 := cumsum(dt)]
dt
   t1 t3  t7
1:  0 12  25
2:  0 17  73
3:  0 25  80
4:  0 34  89
5:  0 39 103

所需的输出如下:

dt
   t1 t3 t7
1:  0 12 37
2:  0  5 53
3:  0  8 15
4:  0  9 18
5:  0  5 19

2 个答案:

答案 0 :(得分:4)

另一个选项使用Reduceaccumulate=TRUE

dt[, names(dt) := Reduce(`+`, dt, accumulate = TRUE)]

dt
#   t1 t3 t7
#1:  0 12 37
#2:  0  5 53
#3:  0  8 15
#4:  0  9 18
#5:  0  5 19

答案 1 :(得分:1)

如果我们需要按行执行此操作,则一个选项是逐行unlist,获取cumsum,转换为list并将其分配给列

dt[, (1:3) := as.list(cumsum(unlist(.SD))), 1:nrow(dt)]
dt
#    t1 t3 t7
#1:  0 12 37
#2:  0  5 53
#3:  0  8 15
#4:  0  9 18
#5:  0  5 19

另一个选项是来自rowCumsums的{​​{1}},可以应用于matrixStats

matrix