有没有办法使用 purrr r dplyr 在 R 中基于两个组添加行?

Is there a way to add rows based on two groups in R using purr or dplyr?

我有一个数据集,为了方便起见,我简化成这样...

Group, Type, Quantity 
1, A, 5
1, B, 8
1, C, 9
1, D, 10
2, A, 7
2, B, 6
2, C, 4
2, E, 5

有没有办法让我按类型添加数量但按组分组?意思是,我有没有办法将 C 的所有数量实例添加到 B 的数量但按组分组?那么有没有办法让数据集看起来像这样呢?我知道我需要使用 map (purr) 或 across (dplyr),但我似乎无法弄清楚。谢谢

Group, Type, Quantity 
1, A, 5
1, B + C, 8 + 9 = 17
1, D, 10
2, A, 7
2, B + C, 6 + 4 = 10
2, E, 5
df %>%
  group_by(Group, gr = recode(Type, C = 'B'))%>%
  summarise(Type = str_c(Type, collapse = '+'),
            Q = sum(Quantity),.groups = 'drop')%>%
  select(-gr)
# A tibble: 6 x 3
  Group Type      Q
  <int> <chr> <int>
1     1 A         5
2     1 B+C      17
3     1 D        10
4     2 A         7
5     2 B+C      10
6     2 E         5