0

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
Dmando
  • 3
  • 1

1 Answers1

1
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
Onyambu
  • 67,392
  • 3
  • 24
  • 53
  • Thank you, this helped a lot, is there a way to do this using the map or across functions? Just curious to know? – Dmando Nov 11 '21 at 21:55
  • What exactly do yoou mean by `map` or `across`?? You only have one column. `across` and `map` are used when you are doing the same thing to multiple columns – Onyambu Nov 11 '21 at 22:00