nest_group_by: Group nested data frames by one or more variables

View source: R/nest_group-by.R

nest_group_byR Documentation

Group nested data frames by one or more variables

Description

nest_group_by() takes a set of nested tbls and converts it to a set of nested grouped tbls where operations are performed "by group". nest_ungroup() removes grouping.

Usage

nest_group_by(.data, .nest_data, ..., .add = FALSE, .drop = TRUE)

nest_ungroup(.data, .nest_data, ...)

Arguments

.data

A data frame, data frame extension (e.g., a tibble), or a lazy data frame (e.g., from dbplyr or dtplyr).

.nest_data

A list-column containing data frames

...

In nest_group_by(), variables or computations to group by. Computations are always done on the ungrouped data frames. To perform computations on the grouped data, you need to use a separate mutate() step after the group_by(). In nest_ungroup(), variables to remove from the grouping.

.add

When FALSE (the default), nest_group_by() will override the existing groups. To add to the existing groups, use .add = TRUE.

.drop

Drop groups formed by factor levels that don't appear in the data? The default is TRUE except when .nest_data has been previously grouped with .drop = FALSE. See dplyr::group_by_drop_default() for details.

Details

nest_group_by() and nest_ungroup() are largely wrappers for dplyr::group_by() and dplyr::ungroup() and maintain the functionality of group_by() and ungroup() within each nested data frame. For more information on group_by() or ungroup(), please refer to the documentation in dplyr.

Value

An object of the same type as .data. Each object in the column .nest_data will be returned as a grouped data frame with class grouped_df, unless the combination of ... and .add yields an empty set of grouping columns, in which case a tibble will be returned.

Examples

gm_nest <- gapminder::gapminder %>% tidyr::nest(country_data = -continent)

# grouping doesn't change .nest_data, just .nest_data class:
gm_nest_grouped <-
  gm_nest %>%
  nest_group_by(country_data, year)

gm_nest_grouped

# It changes how it acts with other nplyr verbs:
gm_nest_grouped %>%
  nest_summarise(
    country_data,
    lifeExp = mean(lifeExp),
    pop = mean(pop),
    gdpPercap = mean(gdpPercap)
  )

# ungrouping removes variable groups:
gm_nest_grouped %>% nest_ungroup(country_data)

nplyr documentation built on Feb. 16, 2023, 7:24 p.m.