8

I have data containing columns biweek and Total, I want to get cumulative sum on biweek basis. My data is like:

biweek  Total
0   3060.913
1   4394.163
2   3413.748
3   2917.548
4   3442.055
5   3348.398
6   1771.722

and I want to get output like :

biweek  Total
0   3060.913
1   7455.076
2   10868.824
3   13786.372
4   17228.427
5   20576.825
6   22348.547

So it there a possible way to achieve it?

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
user6559913
  • 483
  • 4
  • 7
  • 15

1 Answers1

33
# replace the second column for the cumsum of the initial second column
data[, 2] <- cumsum(data[, 2])
Cristóbal Alcázar
  • 1,153
  • 14
  • 26
  • Is it possible to do this based on multiple columns? For instance, with data.tabel, based on multiple columns can be: `DF[, Cumm := cumsum(ColA), by=list(ColB, ColC)]` How about in dataframes? – PM0087 Mar 30 '21 at 18:35
  • Maybe you can sum multiple columns first, like `mtcars[, 1] + mtcars[, 2]`, and then apply `cumsum()`? – Cristóbal Alcázar Mar 31 '21 at 00:34