【问题标题】:percentage count by group using dplyr使用 dplyr 按组计数的百分比
【发布时间】:2017-03-18 12:50:15
【问题描述】:

带有df 的数据框,如下所示

df <- data.frame(colors = c("red", "blue", "green", "red", "red" , "blue"))

我可以使用 dplyr 找出每种颜色的计数,如下所示

df %>%
  group_by(color) %>%
    summarise(count = n())

我需要找到每种颜色的百分比计数而不是计数 - 如何使用 dplyr 来解决它?

【问题讨论】:

  • 使用prop.table并乘以100

标签: r dplyr


【解决方案1】:

您可以通过管道将其发送到 mutate( prop = count / sum(count) ) 或直接在 summarise 中使用 nrow(.)。像这样的:

df %>%
  group_by(colors) %>%
  summarise(count = n() / nrow(.) )

df %>%
  group_by(colors) %>%
  summarise(count = n() ) %>%
  mutate( prop = count / sum(count) )

【讨论】:

  • 您能否详细说明nrow(.)中使用的点(.)
  • . 代表整个数据框(df 这里)
猜你喜欢
  • 2022-12-12
  • 1970-01-01
  • 1970-01-01
  • 2020-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多