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

如何使用dplyr创建汇总其他因子水平总数值的新因子水平

dplyr实现方案

示例数据构造

library(dplyr)
df <- tibble(
  year = c(2019, 2019, 2020, 2020),
  sex = c("M", "F", "M", "F"),
  value = c(10, 20, 50, 20)
)

方案1:行绑定汇总结果(易读性最高)

df %>%
  # 拼接按year分组的汇总行
  bind_rows(
    df %>%
      group_by(year) %>%
      summarise(sex = "Total", value = sum(value))
  ) %>%
  # 按year、sex排序得到要求的输出顺序
  arrange(year, sex)

方案2:组内追加汇总行(写法更简洁)

df %>%
  group_by(year) %>%
  group_modify(~ bind_rows(.x, tibble(sex = "Total", value = sum(.x$value)))) %>%
  ungroup()

两种方案输出结果均和期望格式完全匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 23:09:02