Alanq Alanq - 4 months ago 17
R Question

calculate proportion in grouped data frame

I have the following data frame :

year owngun N
1 2000 Yes 603
2 2000 No 1231
3 2000 Refused 23
4 2012 Yes 440
5 2012 No 841
6 2012 Refused 24


How can I make a column to have the proportions for each
year
and level of
owngun
?

Answer

Assuming your N's are already your aggregated counts, you could get proportions using data.table:

library(data.table)
setDT(df)[,prop:=N/sum(N),by=year]
df

   year  owngun    N       prop
1: 2000     Yes  603 0.32471729
2: 2000      No 1231 0.66289715
3: 2000 Refused   23 0.01238557
4: 2012     Yes  440 0.33716475
5: 2012      No  841 0.64444444
6: 2012 Refused   24 0.01839080

Same approach using plyr:

library(plyr)     
df2<-ddply(df,.(year),transform,prop=N/sum(N))