We use add=TRUE in the second group_by to group by 3 variables, adding c in the OP example -
df %>% group_by(a, b) %>% mutate(x = sum(d)) %>% group_by(c, add=TRUE) %>% mutate(y = sum(e))
According to the documentation for ?group_by
By default, when add = FALSE, group_by overrides existing groups. To add to existing groups instead, use add = TRUE
This can be done with a single call to group_by , but only with non-dplyrish functions:
df %>% group_by(a, b) %>% mutate(x = sum(d), y = ave(e, c, sum))
akrun source share