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
ave(df$num,df$group1,FUN=cumsum)
for summing on justgroup1
orave(df$num,df$group1,df$group2,FUN=cumsum)
for both groups. – Yoghurtdata.table
setDT(data)[, cumsum(num), list(group1, group2)]
ordata %>% group_by(group1, group2) %>% mutate(sum=cumsum(num))
withdplyr
– Hosfmannave
has option forFUN
! – Cassidycassiedata.table
ordplyr
.dplyr
is created to make things easier to understand. – Hosfmanndplyr
, Well, its name is already difficult to understand. Haven't found out whatdplyr
stands for. – Cassidycassieplier
– Hosfmann