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 separatemutate()
step after thegroup_by()
. Innest_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
. Seedplyr::group_by_drop_default()
for details.
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.
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
.
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
#> # A tibble: 5 × 2
#> continent country_data
#> <fct> <list>
#> 1 Asia <gropd_df [396 × 5]>
#> 2 Europe <gropd_df [360 × 5]>
#> 3 Africa <gropd_df [624 × 5]>
#> 4 Americas <gropd_df [300 × 5]>
#> 5 Oceania <gropd_df [24 × 5]>
# 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)
)
#> # A tibble: 5 × 2
#> continent country_data
#> <fct> <list>
#> 1 Asia <tibble [12 × 4]>
#> 2 Europe <tibble [12 × 4]>
#> 3 Africa <tibble [12 × 4]>
#> 4 Americas <tibble [12 × 4]>
#> 5 Oceania <tibble [12 × 4]>
# ungrouping removes variable groups:
gm_nest_grouped %>% nest_ungroup(country_data)
#> # A tibble: 5 × 2
#> continent country_data
#> <fct> <list>
#> 1 Asia <tibble [396 × 5]>
#> 2 Europe <tibble [360 × 5]>
#> 3 Africa <tibble [624 × 5]>
#> 4 Americas <tibble [300 × 5]>
#> 5 Oceania <tibble [24 × 5]>