Nest a tibble using a grouping specification

group_nest(.tbl, ..., .key = "data", keep = FALSE)

Arguments

.tbl

A tbl

...

Grouping specification, forwarded to group_by()

.key

the name of the list column

keep

Should the grouping columns be kept in the list column.

Value

A tbl with one row per unique combination of the grouping variables. The first columns are the grouping variables, followed by a list column of tibbles with matching rows of the remaining columns.

Details

Experimental lifecycle

Grouped data frames

The primary use case for group_nest() is with already grouped data frames, typically a result of group_by(). In this case group_nest() only uses the first argument, the grouped tibble, and warns when ... is used.

Ungrouped data frames

When used on ungrouped data frames, group_nest() forwards the ... to group_by() before nesting, therefore the ... are subject to the data mask.

See also

Examples

#----- use case 1: a grouped data frame iris %>% group_by(Species) %>% group_nest()
#> # A tibble: 3 x 2 #> Species data #> <fct> <list> #> 1 setosa <tibble [50 × 4]> #> 2 versicolor <tibble [50 × 4]> #> 3 virginica <tibble [50 × 4]>
# this can be useful if the grouped data has been altered before nesting iris %>% group_by(Species) %>% filter(Sepal.Length > mean(Sepal.Length)) %>% group_nest()
#> # A tibble: 3 x 2 #> Species data #> <fct> <list> #> 1 setosa <tibble [22 × 4]> #> 2 versicolor <tibble [24 × 4]> #> 3 virginica <tibble [22 × 4]>
#----- use case 2: using group_nest() on a ungrouped data frame with # a grouping specification that uses the data mask starwars %>% group_nest(species, homeworld)
#> # A tibble: 58 x 3 #> species homeworld data #> <chr> <chr> <list> #> 1 Aleena Aleen Minor <tibble [1 × 11]> #> 2 Besalisk Ojom <tibble [1 × 11]> #> 3 Cerean Cerea <tibble [1 × 11]> #> 4 Chagrian Champala <tibble [1 × 11]> #> 5 Clawdite Zolan <tibble [1 × 11]> #> 6 Droid Naboo <tibble [1 × 11]> #> 7 Droid Tatooine <tibble [2 × 11]> #> 8 Droid <NA> <tibble [2 × 11]> #> 9 Dug Malastare <tibble [1 × 11]> #> 10 Ewok Endor <tibble [1 × 11]> #> # … with 48 more rows