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

如何修改dplyr代码仅为生成的n列添加总计行?

解决方案

问题原因

adorn_totals("row")默认会为所有列填充总计标识(默认是"Total"),导致分组列col1、col2也被替换为总计文本,不符合你仅在n列添加总计的需求。

方法1:手动添加总计行(灵活可控)

先完成分组统计,再手动构造总计行并绑定到结果末尾,可自定义分组列的显示内容:

library(dplyr)

data %>% 
  # 先重编码col1,再分组(避免分组内重复执行重编码)
  mutate(col1 = recode(col1, 
                       'R (change file name)' = 'R', 
                       'L (change name e data EEG file)' = 'L')) %>% 
  group_by(col1, col2) %>% 
  summarise(n = n(), .groups = "drop") %>% 
  # 绑定总计行,自定义col1/col2的显示样式
  bind_rows(tibble(col1 = "总计", col2 = NA, n = sum(.$n)))

运行后结果示例:

# A tibble: 5 × 3
  col1  col2     n
  <chr> <dbl> <int>
1 L         2     1
2 R         1     4
3 R         2     3
4 R         3     2
5 总计     NA    10

方法2:基于janitor修改总计行

如果坚持使用janitor,可以在添加总计后手动调整分组列的内容:

library(dplyr)
library(janitor)

data %>% 
  mutate(col1 = recode(col1, 
                       'R (change file name)' = 'R', 
                       'L (change name e data EEG file)' = 'L')) %>% 
  group_by(col1, col2) %>% 
  summarise(n = n(), .groups = "drop") %>% 
  adorn_totals("row") %>% 
  # 修改总计行的col1和col2显示
  mutate(
    col1 = if_else(col1 == "Total", "总计", col1),
    col2 = if_else(col1 == "总计", NA_real_, col2)
  )

注意事项

  • 将mutate(重编码操作)放在group_by之前,避免分组内重复执行相同操作,提升运行效率。
  • summarise时添加.groups = "drop"取消分组状态,避免后续操作受分组逻辑影响。

内容的提问来源于stack exchange,提问作者12666727b9

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 15:45:06