0

I have:

dataDT <- data.table(A = rep(1, 3), B = rep(2, 3), C = rep(3, 3))
dataDT
   A B C
1: 1 2 3
2: 1 2 3
3: 1 2 3

I want to create 3 new columns so that:

dataDT[, A_r := A]
dataDT[, B_r := A + B]
dataDT[, C_r := A + B + C]
dataDT
   A B C A_r B_r C_r
1: 1 2 3   1   3   6
2: 1 2 3   1   3   6
3: 1 2 3   1   3   6

i.e.

  • Each new column is cumulative sum from left to right.
  • If there are x columns originally, then there will be x new columns.

How to achieve it (rather than coding and writing explicitly)?

LeGeniusII
  • 900
  • 1
  • 10
  • 28
  • 2
    Whenever you see something like `A` to `A + B` to `A + B + C` where each new value is combined using a common function, consider `?Reduce`. I'm pretty sure I've seen it applied to this exact problem. One moment... - bingo: possible duplicate - https://stackoverflow.com/questions/46978826/cumulative-sum-across-columns-instead-of-rows – thelatemail Sep 13 '19 at 05:04
  • 2
    isn't this just `cumsum` row-wise you need to `cbind`, `t(apply(dataDT, 1, cumsum))` to your original data. – Ronak Shah Sep 13 '19 at 05:05

0 Answers0