dplyr and tidyr to unnest a nested list column?library(dplyr) library(tidyr) df <- tibble(id = 1:2, data = list(tibble(x = 1:2), tibble(x = 3:4))) unnest(df, data)
The unnest() function expands the nested data column, which contains tibbles, into multiple rows. Each row in the nested tibble becomes a separate row in the output, repeating the id accordingly.
library(dplyr) library(tidyr) df <- tibble(group = c('A', 'A', 'B'), value = 1:3) nested <- df %>% group_by(group) %>% nest() unnest(nested, data)
After nesting, the data is grouped by group with nested tibbles. Unnesting expands these nested tibbles back into rows, repeating the group values accordingly.
library(tidyr) df <- tibble(id = 1:2, vals = list(1:3, 4:5)) unnest(df, vals, keep_empty = TRUE)
The unnest() function in tidyr does not have a keep_empty argument, so passing it causes an unused argument error.
data in this tibble?library(tidyr) df <- tibble(id = 1:2, data = list(tibble(a = 1:2), tibble(a = 3:4)))
The unnest() function uses tidyselect syntax so unnest(df, cols = data) correctly specifies the column to unnest. Other options use incorrect or deprecated syntax.
library(dplyr) library(tidyr) df <- tibble( group1 = c('X', 'X', 'Y', 'Y'), group2 = c('A', 'B', 'A', 'B'), val = 1:4 ) nested <- df %>% group_by(group1) %>% nest() unnested <- nested %>% unnest(data)
Nesting by group1 creates two nested tibbles, each containing rows for that group. Unnesting expands these back, resulting in the original 4 rows.