Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

with_groups

Perform an operation with temporary groups


Description

[Experimental]

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

Usage

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))
df %>%
  with_groups(g, ~ mutate(.x, x1 = first(x)))

df %>%
  group_by(g) %>%
  with_groups(NULL, mutate, x_mean = mean(x))

# NB: grouping can't be restored if you remove the grouping variables
df %>%
  group_by(g) %>%
  with_groups(NULL, mutate, g = NULL)

dplyr

A Grammar of Data Manipulation

v1.0.6
MIT + file LICENSE
Authors
Hadley Wickham [aut, cre] (<https://orcid.org/0000-0003-4757-117X>), Romain François [aut] (<https://orcid.org/0000-0002-2444-4226>), Lionel Henry [aut], Kirill Müller [aut] (<https://orcid.org/0000-0002-1416-3412>), RStudio [cph, fnd]
Initial release

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.