This was an experimental function that allows you to modify the grouping
variables for a single operation; it is superseded in favour of using the
.by
argument to individual verbs.
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))
# Old
df %>%
with_groups(g, mutate, x_mean = mean(x))
#> # A tibble: 5 × 3
#> g x x_mean
#> <dbl> <dbl> <dbl>
#> 1 1 0.501 0.334
#> 2 1 0.166 0.334
#> 3 2 0.361 0.507
#> 4 2 0.652 0.507
#> 5 3 0.874 0.874
# New
df %>% mutate(x_mean = mean(x), .by = g)
#> # A tibble: 5 × 3
#> g x x_mean
#> <dbl> <dbl> <dbl>
#> 1 1 0.501 0.334
#> 2 1 0.166 0.334
#> 3 2 0.361 0.507
#> 4 2 0.652 0.507
#> 5 3 0.874 0.874