with_groups: Perform an operation with temporary groups

Description Usage Arguments Examples

View source: R/groups-with.R

Description

\Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")}

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

Usage

1
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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
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)

javifar/TIDYVERSE-DPLYR documentation built on Dec. 20, 2021, 9:08 p.m.