Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unnest multiple list columns of a dataframe in one go with dplyr pipe

Tags:

r

dplyr

tidyr

I have the following tibble, which has two nested columns:

library(tidyverse)
df <- structure(list(a = list(c("a", "b"), "c"), b = list(c("1", "2", 
"3"), "3"), c = c(11, 22)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -2L))

Which produces:

# A tibble: 2 x 3
  a         b             c
  <list>    <list>    <dbl>
1 <chr [2]> <chr [3]>    11
2 <chr [1]> <chr [1]>    22

How can I unnest them at once producing one single tibble?

I tried this but fail:

> df %>% unnest(a, b)
Error: All nested columns must have the same number of elements.
like image 221
scamander Avatar asked Mar 03 '23 22:03

scamander


1 Answers

There's probably a cleaner way to do it, but if you want the cartesian product for the columns you can unnest them in sequence, if nothing else:

> df %>% 
    unnest(a, .drop = FALSE) %>% 
    unnest(b, .drop = FALSE)

# # A tibble: 7 x 3
#       c a     b    
#   <dbl> <chr> <chr>
# 1    11 a     1    
# 2    11 a     2    
# 3    11 a     3    
# 4    11 b     1    
# 5    11 b     2    
# 6    11 b     3    
# 7    22 c     3
like image 124
Jared Wilber Avatar answered May 16 '23 08:05

Jared Wilber