cumsum by group

Lovnlust picture Lovnlust · May 16, 2015 · Viewed 11.5k times · Source

Suppose data looks like

group1 group2 num
A      sg     1
A      sh     2
A      sg     4
B      at     3
B      al     7

a <- cumsum(data[,"num"]) # 1 3 7 10 17

I need something accumulated by groups. In reality,I have multiple columns as grouping indicators. I want to get the accumulated sum by the subgroup I define.

E.g

If I group by group1 only, then the output should be

group1 sum
A      1
A      3
A      7
B      3
B      10

If I group by two variables group1,group2 then the output is

group1 group2 sum
A      sg     1
A      sh     2
A      sg     5
B      at     3
B      al     7

Answer

Quinn Weber picture Quinn Weber · May 16, 2015
library(data.table)

data <- data.table(group1=c('A','A','A','B','B'),sum=c(1,2,4,3,7))

data[,list(cumsum = cumsum(sum)),by=list(group1)]