使用 group_by 和汇总查找子组中的百分比 [英] Finding percentage in a sub-group using group_by and summarise
问题描述
我是 dplyr 的新手,并试图在没有任何运气的情况下进行以下转换.我已经在互联网上进行了搜索,我找到了在 ddply 中执行相同操作的示例,但我想使用 dplyr.
I am new to dplyr and trying to do the following transformation without any luck. I've searched across the internet and I have found examples to do the same in ddply but I'd like to use dplyr.
我有以下数据:
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
.. ... ... ...
我想使用 dplyr 来计算每个类型(aaa、bbb、ccc)在一个月级别的百分比,即
I want to use dplyr to calculate the percentage of each type (aaa, bbb, ccc) at a 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 ..
.. ... ... ...
我试过了
data %>%
group_by(month, type) %>%
summarise(count / sum(count))
这给出了一个 1 作为每个值.如何计算当月所有类型的 sum(count) 总和?
This gives a 1 as each value. How do I make the sum(count) sum across all the types in the month?
推荐答案
尝试
library(dplyr)
data %>%
group_by(month) %>%
mutate(countT= sum(count)) %>%
group_by(type, add=TRUE) %>%
mutate(per=paste0(round(100*count/countT,2),'%'))
或者在不创建额外列的情况下使其更简单
Or make it more simpler without creating additional columns
data %>%
group_by(month) %>%
mutate(per = 100 *count/sum(count)) %>%
ungroup
我们也可以在将sum(count)
按'month'汇总后使用left_join
We could also use left_join
after summarising the sum(count)
by 'month'
或者使用 data.table
的选项.
library(data.table)
setkey(setDT(data), month)[data[, list(count=sum(count)), month],
per:= paste0(round(100*count/i.count,2), '%')][]
这篇关于使用 group_by 和汇总查找子组中的百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!