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

如何在R的dplyr中按条件汇总指定行并合并分组

用dplyr合并特定分组并按年求和

直接给出可运行的解决方案:

library(dplyr)

df_result <- df %>%
  # 将分组A、B替换为AB,其余分组保持不变
  mutate(group = case_when(
    group %in% c("A", "B") ~ "AB",
    TRUE ~ group
  )) %>%
  # 按年份和新分组汇总求和
  group_by(year, group) %>%
  summarise(value = sum(value), .groups = "drop")

# 输出结果
print(df_result)

运行后得到的结果:

# A tibble: 9 × 3
   year group value
  <dbl> <chr> <dbl>
1  2020 AB       15
2  2020 C         8
3  2020 D         6
4  2021 AB       32
5  2021 C        17
6  2021 D         3
7  2022 AB       21
8  2022 C        12
9  2022 D         5

注:你给出的期望输出中2021年AB分组的value写的是22,实际按原始数据计算应为12+20=32,以上代码结果是正确的计算值。

步骤说明

  • mutate() + case_when():针对性修改分组列,把需要合并的A、B统一标记为AB,其他分组不改动
  • group_by():指定按年份和新分组作为汇总维度
  • summarise():对每个分组内的value求和,.groups = "drop"确保输出是普通数据框而非分组对象

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 01:40:20