This is an experimental new function that allows you to modify the grouping variables for a single operation.
with_groups(.data, .groups, .f, ...)A data frame
<tidy-select> One or more variables
to group by. Unlike group_by(), you can only group by existing variables,
and you can use tidy-select syntax like c(x, y, z) to select multiple
variables.
Use NULL to temporarily ungroup.
Function to apply to regrouped data.
Supports purrr-style ~ syntax
Additional arguments passed on to ....
df <- tibble(g = c(1, 1, 2, 2, 3), x = runif(5))
df %>%
with_groups(g, mutate, x_mean = mean(x))
#> # A tibble: 5 × 3
#> g x x_mean
#> <dbl> <dbl> <dbl>
#> 1 1 0.710 0.528
#> 2 1 0.346 0.528
#> 3 2 0.0221 0.329
#> 4 2 0.636 0.329
#> 5 3 0.112 0.112
df %>%
with_groups(g, ~ mutate(.x, x1 = first(x)))
#> # A tibble: 5 × 3
#> g x x1
#> <dbl> <dbl> <dbl>
#> 1 1 0.710 0.710
#> 2 1 0.346 0.710
#> 3 2 0.0221 0.0221
#> 4 2 0.636 0.0221
#> 5 3 0.112 0.112
df %>%
group_by(g) %>%
with_groups(NULL, mutate, x_mean = mean(x))
#> # A tibble: 5 × 3
#> # Groups: g [3]
#> g x x_mean
#> <dbl> <dbl> <dbl>
#> 1 1 0.710 0.365
#> 2 1 0.346 0.365
#> 3 2 0.0221 0.365
#> 4 2 0.636 0.365
#> 5 3 0.112 0.365
# NB: grouping can't be restored if you remove the grouping variables
df %>%
group_by(g) %>%
with_groups(NULL, mutate, g = NULL)
#> # A tibble: 5 × 1
#> x
#> <dbl>
#> 1 0.710
#> 2 0.346
#> 3 0.0221
#> 4 0.636
#> 5 0.112