I have a dataset in R of student weekly allowances by class, which looks like:
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
How can I summarize the results by group (Year/Class) to get sum and % (by group)? Getting sum seems easy with ddply
by just couldn't get the % by group part right.
It works for sum
:
summary <- ddply(my_data, .(Year, Class), summarize, Sum_Allow=sum(Allowance))
But it doesn't work for the percentage by group part:
summary <- ddply(my_data, .(Year, Class), summarize, Sum_Allow=sum(Allowance),
Allow_Pct=Allowance/sum(Allowance))
Ideal result should look like:
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%
I tried ddply from the plyr package, but please let me know of any way that this may work.