Experimental lifecycle

This is an experimental new function that allows you to modify the grouping variables for a single operation.

with_groups(.data, .groups, .f, ...)

Arguments

.data

A data frame

.groups

<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.

.f

Function to apply to regrouped data. Supports purrr-style ~ syntax

...

Additional arguments passed on to ....

Examples

df <- tibble(g = c(1, 1, 2, 2, 3), x = runif(5)) df %>% with_groups(g, mutate, x_mean = mean(x))
#> # A tibble: 5 x 3 #> g x x_mean #> <dbl> <dbl> <dbl> #> 1 1 0.587 0.329 #> 2 1 0.0717 0.329 #> 3 2 0.0935 0.277 #> 4 2 0.460 0.277 #> 5 3 0.568 0.568
df %>% with_groups(g, ~ mutate(.x, x1 = first(x)))
#> # A tibble: 5 x 3 #> g x x1 #> <dbl> <dbl> <dbl> #> 1 1 0.587 0.587 #> 2 1 0.0717 0.587 #> 3 2 0.0935 0.0935 #> 4 2 0.460 0.0935 #> 5 3 0.568 0.568
df %>% group_by(g) %>% with_groups(NULL, mutate, x_mean = mean(x))
#> # A tibble: 5 x 3 #> # Groups: g [3] #> g x x_mean #> <dbl> <dbl> <dbl> #> 1 1 0.587 0.356 #> 2 1 0.0717 0.356 #> 3 2 0.0935 0.356 #> 4 2 0.460 0.356 #> 5 3 0.568 0.356
# 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 x 1 #> x #> <dbl> #> 1 0.587 #> 2 0.0717 #> 3 0.0935 #> 4 0.460 #> 5 0.568