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.828 0.667 #> 2 1 0.507 0.667 #> 3 2 0.186 0.202 #> 4 2 0.218 0.202 #> 5 3 0.522 0.522
df %>% with_groups(g, ~ mutate(.x, x1 = first(x)))
#> # A tibble: 5 x 3 #> g x x1 #> <dbl> <dbl> <dbl> #> 1 1 0.828 0.828 #> 2 1 0.507 0.828 #> 3 2 0.186 0.186 #> 4 2 0.218 0.186 #> 5 3 0.522 0.522
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.828 0.452 #> 2 1 0.507 0.452 #> 3 2 0.186 0.452 #> 4 2 0.218 0.452 #> 5 3 0.522 0.452
# 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.828 #> 2 0.507 #> 3 0.186 #> 4 0.218 #> 5 0.522