R - 设置 group_by / 将值汇总为组成员的新列

R - set group_by / summarize values as new column on group members

如何将 group_by + summarize 的结果应用/设置为该组所有观测值的新变量?

假设我有一个 tibble 如下所示:

foo <- tribble(
    ~x, ~y, 
     1, 1, 
     1, 5, 
     1, 2,  
     2, 1, 
     2, 7, 
     2, 3)

x表示组,y一个变量。
我知道我可以通过 foo %>% group_by(x) %>% summarize(max(y)).

获得每个组的 max-y

现在如何将此结果设置为整个组的新列?
IE。结果

~x, ~y, ~max-y
 1,  1,  5
 1,  5,  5
 1,  2,  5
 2,  1,  7
 2,  7,  7
 2,  3,  7

可以简单地在 group by 之后使用 mutate 并指定函数:

foo %>%
  group_by(x) %>%
  mutate(max_y = max(y))
#output:
# A tibble: 6 x 3
# Groups:   x [2]
      x     y max_y
  <dbl> <dbl> <dbl>
1     1     1     5
2     1     5     5
3     1     2     5
4     2     1     7
5     2     7     7
6     2     3     7