【发布时间】:2014-12-24 10:03:27
【问题描述】:
我在 R 中有一个按班级划分的学生每周津贴数据集,如下所示:
Year ID Class Allowance
2013 123 Freshman 100
2013 234 Freshman 110
2013 345 Sophomore 150
2013 456 Sophomore 200
2013 567 Junior 250
2014 678 Junior 100
2014 789 Junior 230
2014 890 Freshman 110
2014 891 Freshman 250
2014 892 Sophomore 220
如何按组(年份/班级)汇总结果以获得总和和百分比(按组)?使用ddply 获得总和似乎很容易,只是无法正确获得按组的百分比。
它适用于sum:
summary <- ddply(my_data, .(Year, Class), summarize, Sum_Allow=sum(Allowance))
但它不适用于按组部分的百分比:
summary <- ddply(my_data, .(Year, Class), summarize, Sum_Allow=sum(Allowance),
Allow_Pct=Allowance/sum(Allowance))
理想的结果应该是这样的:
Year Class Sum_Allow Allow_Pct
2013 Freshman 210 26%
2013 Junior 250 31%
2013 Sophomore 350 43%
2014 Freshman 360 40%
2014 Junior 330 36%
2014 Sophomore 220 24%
我尝试了 plyr 包中的 ddply,但请告诉我任何可行的方法。
【问题讨论】:
-
您正在尝试绑定具有奇数行数的数据帧。分别执行
Sum_allow和allow_pct并查看结果。您可以使用 head 或 tail 来获取每个百分比的第一行或最后一行
标签: r plyr aggregation