Nesting and Unnesting Data Frames
Use nest() and unnest() to work with list-columns in tidy workflows.
List-Columns and Nested Data
A list-column is a column in a data frame where each cell contains an R object (a vector, data frame, model, or list). This makes it possible to store structured sub-data alongside other columns, enabling powerful group-wise workflows.
library(tidyr)
library(dplyr)
# A simple data frame with a list-column
df <- data.frame(
group = c('A','B','C'),
n = c(3, 2, 4)
)
df$values <- list(c(1,2,3), c(4,5), c(6,7,8,9))
print(df)
print(df$values[[1]]) # Access the first list elementnest() — Creating Nested Data Frames
nest(df, data = c(col1, col2)) groups rows by the non-nested columns and packs the specified columns into a list-column of data frames. One row per group, each containing a mini data frame.
library(tidyr)
library(dplyr)
df <- data.frame(
region = c('East','East','East','West','West'),
month = c(1,2,3,1,2),
sales = c(100,120,110,200,190)
)
nested <- df %>%
nest(data = c(month, sales))
print(nested)
print(nested$data[[1]]) # East region's dataAll lessons in this course
- Wide to Long with pivot_longer()
- Long to Wide with pivot_wider()
- separate() and unite() for String Columns
- Nesting and Unnesting Data Frames