我在 R 中有一个按类(class)划分的学生每周津贴数据集,如下所示:
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
如何按组(年份/类(class))汇总结果以获得总和和百分比(按组)?使用 ddply 获取总和似乎很容易,只是无法正确获取按组部分的百分比。
它适用于总和
:
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,但请告诉我任何可行的方法。
最佳答案
这是使用 data.table
包的可能解决方案(假设您的数据名为 df
)
library(data.table)
setDT(df)[, list(Sum_Allow = sum(Allowance)), keyby = list(Year, Class)][,
Allow_Pct := paste0(round(Sum_Allow/sum(Sum_Allow), 2)*100, "%"), by = Year][]
# Year Class Sum_Allow Allow_Pct
# 1: 2013 Freshman 210 26%
# 2: 2013 Junior 250 31%
# 3: 2013 Sophomore 350 43%
# 4: 2014 Freshman 360 40%
# 5: 2014 Junior 330 36%
# 6: 2014 Sophomore 220 24%
<小时/>
贡献给@rawr,这是一个可能的基本 R 解决方案
df2 <- aggregate(Allowance ~ Class + Year, df, sum)
transform(df2, Allow_pct = ave(Allowance, Year, FUN = function(x) paste0(round(x/sum(x), 2)*100, "%")))
# Class Year Allowance Allow_pct
# 1 Freshman 2013 210 26%
# 2 Junior 2013 250 31%
# 3 Sophomore 2013 350 43%
# 4 Freshman 2014 360 40%
# 5 Junior 2014 330 36%
# 6 Sophomore 2014 220 24%
关于r - 按组进行聚合和百分比计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26617843/