Rowwise cumulative sum
Asked Answered
C

2

5

I have a data.table dt as follows.

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

I want to get the cumulative sums across the columns. I am only getting it across the rows. How to do this in 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

The desired output is as follows:

dt
   t1 t3 t7
1:  0 12 37
2:  0  5 53
3:  0  8 15
4:  0  9 18
5:  0  5 19
Chromolithography answered 27/10, 2017 at 15:42 Comment(1)
setDT(df) converts in place, no need to assignMayflower
O
9

Another option use Reduce with accumulate=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
Obsequious answered 27/10, 2017 at 15:50 Comment(1)
based on a couple of tests, this method vastly outperforms the others speed-wiseLuannaluanne
S
2

If we need to do this by row, then one option is group by row, unlist, get the cumsum, convert to list and assign it to the columns

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

Or another option is rowCumsums from matrixStats, which can be applied to a matrix

library(matrixStats)
dt[, (1:3) := as.data.table(rowCumsums(as.matrix(.SD)))]
Subantarctic answered 27/10, 2017 at 15:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.