https://github.com/hadley/dplyr
Raw File
Tip revision: 5e3f3ec7dd464d9251d2ec8eb9a3c31624130580 authored by Hadley Wickham on 28 May 2020, 23:52:31 UTC
Increment version number
Tip revision: 5e3f3ec
with_groups.Rd
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/groups-with.R
\name{with_groups}
\alias{with_groups}
\title{Perform an operation with temporary groups}
\usage{
with_groups(.data, .groups, .f, ...)
}
\arguments{
\item{.data}{A data frame}

\item{.groups}{<\code{\link[=dplyr_tidy_select]{tidy-select}}> One or more variables
to group by. Unlike \code{\link[=group_by]{group_by()}}, you can only group by existing variables,
and you can use tidy-select syntax like \code{c(x, y, z)} to select multiple
variables.

Use \code{NULL} to temporarily \strong{un}group.}

\item{.f}{Function to apply to regrouped data.
Supports purrr-style \code{~} syntax}

\item{...}{Additional arguments passed on to \code{...}.}
}
\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.
}
\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)
}
back to top