r - Finding percentage in a sub-group using group_by and summarise -
i new dplyr , trying following transformation without luck. i've searched across internet , have found examples same in ddply i'd use dplyr.
i have following data:
month type count 1 feb-14 bbb 341 2 feb-14 ccc 527 3 feb-14 aaa 2674 4 mar-14 bbb 811 5 mar-14 ccc 1045 6 mar-14 aaa 4417 7 apr-14 bbb 1178 8 apr-14 ccc 1192 9 apr-14 aaa 4793 10 may-14 bbb 916 .. ... ... ...
i want use dplyr calculate percentage of each type (aaa, bbb, ccc) @ month level i.e.
month type count per 1 feb-14 bbb 341 9.6% 2 feb-14 ccc 527 14.87% 3 feb-14 aaa 2674 .. .. ... ... ...
i've tried
data %>% group_by(month, type) %>% summarise(count / sum(count))
this gives 1 each value. how make sum(count) sum across types in month?
try
library(dplyr) data %>% group_by(month) %>% mutate(countt= sum(count)) %>% group_by(type, add=true) %>% mutate(per=paste0(round(100*count/countt,2),'%'))
we use left_join
after summarising sum(count)
'month'
or option using data.table
.
library(data.table) setkey(setdt(data), month)[data[, list(count=sum(count)), month], per:= paste0(round(100*count/i.count,2), '%')][]