You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用R语言按月分组计算多代码问题的Yes响应占比?

解决方案:生成按月统计的多代码响应占比列联表

需求说明

我有一个按月份记录多代码问题响应的DataFrame,其中1代表“Yes”,0代表“No”。需要生成一份带百分比的列联表,展示每个多代码列中按月统计的“Yes”(即1)响应占比。示例数据结构如下:

| Month | Multicode_1| .... | Multicode_n|
| --- | .......... | .... | .......... |
| Jan22 | 1 | .... | .......... |
| Feb22 | 0 | .... | .......... |

我尝试了以下R代码,但未完全实现需求:

ex8 <- NPSSurvey_df %>%
  group_by(Month) %>% filter(Pack == "Sports", CustomerType == "New") %>%
  summarise(across(Vid_Freeze:Mistake))
head(ex8)

修正后的R代码

要实现按月统计各多代码列的“Yes”占比,你可以在summarise的across逻辑里直接计算比例并格式化百分比:

# 筛选目标数据并按月计算各多代码列的Yes占比
ex8 <- NPSSurvey_df %>%
  filter(Pack == "Sports", CustomerType == "New") %>%
  group_by(Month) %>%
  summarise(
    across(Vid_Freeze:Mistake, 
           ~ mean(.x, na.rm = TRUE) %>% scales::percent(accuracy = 1)),
    .groups = "drop"  # 取消分组状态,输出整洁表格
  )

# 查看结果
head(ex8)

代码说明

  • 先filter再group_by更高效,减少分组计算的数据量
  • mean(.x, na.rm = TRUE):0和1的均值直接等于1的占比,na.rm=TRUE自动忽略缺失值
  • scales::percent(accuracy = 1):把比例转为带百分号的字符串,accuracy=1控制百分比保留整数位
  • .groups = "drop":分组统计后取消分组,避免后续操作受分组状态影响

扩展:同时显示计数与百分比

如果需要每个单元格同时展示"Yes"的数量和占比,可以调整代码如下:

ex8_with_counts <- NPSSurvey_df %>%
  filter(Pack == "Sports", CustomerType == "New") %>%
  group_by(Month) %>%
  summarise(
    across(Vid_Freeze:Mistake, 
           ~ paste0(sum(.x, na.rm = TRUE), " (", scales::percent(mean(.x, na.rm = TRUE), accuracy = 1), ")")),
    .groups = "drop"
  )

head(ex8_with_counts)

输出的单元格格式会变为「Yes数量 (百分比)」,更直观展示统计细节。

内容的提问来源于stack exchange,提问作者Andrew Davies

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 09:35:23