How to get the cumulative sum by group in R?

前端 未结 2 373
北恋
北恋 2020-12-03 05:21

Suppose I have a dataframe such that:

df<-data.frame(id=1:8,group=c(1,0,0,1,1,0,1,0),rep=c(rep(\"d1\",4),rep(\"d2\",4)),value=rbinom(8,1,0.6))
df
  id gro         


        
2条回答
  •  一向
    一向 (楼主)
    2020-12-03 05:49

    library(data.table)
    
    # convert to data.table in place
    setDT(df)
    
    # dcast and do individual sums
    dt.cast = dcast.data.table(df, group ~ rep, value.var = 'value',
                               fun.aggregate = sum)
    dt.cast
    #   group d1 d2
    #1:     0  0  1
    #2:     1  1  2
    
    # cumsum
    dt.cast[, as.list(cumsum(unlist(.SD))), by = group]
    #   group d1 d2
    #1:     0  0  1
    #2:     1  1  3
    

提交回复
热议问题