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

Time:11-12

I have a dataset, that, to make it easier I have simplified like this...

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

Is there a way for me to add Quantity by Type but grouped by Group? Meaning, is there a way for me to add all instances of quantity for C to quantity for B but grouped by Group? So is there a way for the dataset to look like this? I know I need to use map (purr) or across (dplyr), but I can't seem to figure it out. Thanks.

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

CodePudding user response:

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
  • Related