按组累计 [英] cumsum by group
本文介绍了按组累计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设数据看起来像
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.
例如
如果我只按group1
分组,那么输出应该是
If I group by group1
only, then the output should be
group1 sum
A 1
A 3
A 7
B 3
B 10
如果我按两个变量分组 group1,group2
那么输出是
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
推荐答案
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)]
这篇关于按组累计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文