使用dplyr按组计算的百分比 [英] percentage count by group using dplyr
本文介绍了使用dplyr按组计算的百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
具有数据框 df
如下
df <- data.frame(colors = c("red", "blue", "green", "red", "red" , "blue"))
我可以使用dplyr找出每种颜色的计数,如下所示:
I can find out the count per color using dplyr as follows
df %>%
group_by(color) %>%
summarise(count = n())
我需要找到每种颜色的百分比计数,而不是计数-如何使用dplyr处理它?</ p>
Instead of count I need to find the percentage count for each color - how to go about it using dplyr ?
推荐答案
您可以将其通过管道传递到 mutate(prop = count / sum(count))
或直接在 summary $ c $之内c>和
nrow(。)
。像这样:
You can either pipe this to a mutate( prop = count / sum(count) )
or directly within summarise
with nrow(.)
. Something like this:
df %>%
group_by(colors) %>%
summarise(count = n() / nrow(.) )
或
df %>%
group_by(colors) %>%
summarise(count = n() ) %>%
mutate( prop = count / sum(count) )
这篇关于使用dplyr按组计算的百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文