r中按条件求和的值
我一直在努力解决这个问题,但我找不到解决这个问题的正确方法。假设我有一些数据如下所示:r中按条件求和的值,r,R,我一直在努力解决这个问题,但我找不到解决这个问题的正确方法。假设我有一些数据如下所示: hhid totalplacevisited 1 5 1 6 1 2 2 2 2 4 3 1 如何聚合数据,以便获得以下格式的值: hhid totalplacevisited totalplacedvisitedbyhh 1
hhid totalplacevisited
1 5
1 6
1 2
2 2
2 4
3 1
如何聚合数据,以便获得以下格式的值:
hhid totalplacevisited totalplacedvisitedbyhh
1 5 13
1 6 13
1 2 13
2 2 6
2 4 6
3 1 1
一种选择是使用ave
另一种选择是使用data.table
data.table包是最快的方式:
dt = data.table(df)
dt[,totalplacesvisitedbyhh:=sum(totalplacevisited),by=hhid]
这是plyr软件包的解决方案
library(plyr)
ddply(mydf,.(hhid),transform, totalplacedvisitedbyhh=sum(totalplacevisited))
hhid totalplacevisited totalplacedvisitedbyhh
1 1 5 13
2 1 6 13
3 1 2 13
4 2 2 6
5 2 4 6
6 3 1 1
“我怎样才能聚合”–使用聚合是合适的。谢谢,ave工作得很好
dt = data.table(df)
dt[,totalplacesvisitedbyhh:=sum(totalplacevisited),by=hhid]
library(plyr)
ddply(mydf,.(hhid),transform, totalplacedvisitedbyhh=sum(totalplacevisited))
hhid totalplacevisited totalplacedvisitedbyhh
1 1 5 13
2 1 6 13
3 1 2 13
4 2 2 6
5 2 4 6
6 3 1 1