nest_by: Nest by one or more variables

View source: R/nest-by.R

nest_byR Documentation

Nest by one or more variables



nest_by() is closely related to group_by(). However, instead of storing the group structure in the metadata, it is made explicit in the data, giving each group key a single row along with a list-column of data frames that contain all the other data.

nest_by() returns a rowwise data frame, which makes operations on the grouped data particularly elegant. See vignette("rowwise") for more details.


nest_by(.data, ..., .key = "data", .keep = FALSE)



A data frame, data frame extension (e.g. a tibble), or a lazy data frame (e.g. from dbplyr or dtplyr). See Methods, below, for more details.


In group_by(), variables or computations to group by. Computations are always done on the ungrouped data frame. To perform computations on the grouped data, you need to use a separate mutate() step before the group_by(). Computations are not allowed in nest_by(). In ungroup(), variables to remove from the grouping.


Name of the list column


Should the grouping columns be kept in the list column.


Note that df %>% nest_by(x, y) is roughly equivalent to

df %>%
  group_by(x, y) %>%
  summarise(data = list(pick(everything()))) %>%

If you want to unnest a nested data frame, you can either use tidyr::unnest() or take advantage of reframe()s multi-row behaviour:

nested %>%


A rowwise data frame. The output has the following properties:

  • The rows come from the underlying group_keys().

  • The columns are the grouping keys plus one list-column of data frames.

  • Data frame attributes are not preserved, because nest_by() fundamentally creates a new data frame.

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.


nest_by() is not stable because tidyr::nest(.by =) provides very similar behavior. It may be deprecated in the future.


This function is a generic, which means that packages can provide implementations (methods) for other classes. See the documentation of individual methods for extra arguments and differences in behaviour.

The following methods are currently available in loaded packages: \Sexpr[stage=render,results=rd]{dplyr:::methods_rd("nest_by")}.


# After nesting, you get one row per group
iris %>% nest_by(Species)
starwars %>% nest_by(species)

# The output is grouped by row, which makes modelling particularly easy
models <- mtcars %>%
  nest_by(cyl) %>%
  mutate(model = list(lm(mpg ~ wt, data = data)))

models %>% summarise(rsq = summary(model)$r.squared)

# This is particularly elegant with the broom functions
models %>% summarise(broom::glance(model))
models %>% reframe(broom::tidy(model))

# Note that you can also `reframe()` to unnest the data
models %>% reframe(data)

dplyr documentation built on Nov. 17, 2023, 5:08 p.m.