【问题标题】:How to compute percentage within groups如何计算组内百分比
【发布时间】:2022-11-21 05:37:39
【问题描述】:

在按部门划分的包含员工的数据集中,我试图计算每个部门和工作角色的员工总数除以女性或男性组的员工总数。

最终结果应该按女性和男性水平划分。在女性和男性下,列出了三个不同的部门。在纵向上,我列出了四种不同的工作角色。每个单元格都包含一个总百分比值。

例如,如果共有 100 名女性和 4 人担任妇产科护士角色,则该特定单元格将显示 4%。

我在将数据汇总为这种格式时做错了什么?

我当前的代码:

library(dplyr)

attr_per <- heatmap_data %>% 
  group_by(Department, JobRole, Gender) %>% 
  mutate(Percent = sum(Attrition == "Yes")/n()) %>% 
  summarize(Department, JobRole, Gender, Percent)

最终目标是使用这些数据制作热图。

【问题讨论】:

  • 试试attr_per &lt;- heatmap_data %&gt;% group_by(Department, JobRole, Gender) %&gt;% summarise(Percent = sum(Attrition == "Yes") / n())
  • 《百女四人》……女人不是人吗?
  • 请提供来自dput(head(heatmap_data)) 的输出,它会帮助您了解开始的内容。您还可以包括一个输出应该是什么的明确示例吗?

标签: r dplyr


【解决方案1】:

总结你的计数,然后以百分比的形式变化。

您可能希望将 Attrition 设为计算值,例如 gorup_by(..., Attrition = Attrition == "yes")

library(dplyr)
heatmap_data |>
  group_by(Department, JobRole, Category, Attrition) |>
  summarise(count = n()) |>
  # may want to reset the grouping variables here
  mutate(Percent = count/sum(count))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2022-07-11
    • 1970-01-01
    • 2017-11-12
    • 2021-04-12
    相关资源
    最近更新 更多