How to reshape a column of a list of two tibbles into two columns each contains a list of tibble?

library(tidyverse)

original_tb <- tibble(id = 1:3, y = list(list(mtcars = as_tibble(sample_n(mtcars, 10)), diamonds = as_tibble(sample_n(diamonds, 15)))) )

expected_tb <- tibble(id = 1:3, mtcars = list(as_tibble(sample_n(mtcars, 10))), diamonds = list(as_tibble(sample_n(diamonds, 15))))

With last version of dplyr (>= 0.8.0) you can do that using new group_map function

library(tidyverse)

original_tb <- tibble(id = 1:3, y = list(list(mtcars = as_tibble(sample_n(mtcars, 10)), diamonds = as_tibble(sample_n(diamonds, 15)))) )

expected_tb <- tibble(id = 1:3, mtcars = list(as_tibble(sample_n(mtcars, 10))), diamonds = list(as_tibble(sample_n(diamonds, 15))))

# with new dplyr > 0.8.0
original_tb %>%
  group_by(id) %>%
  group_map( ~ pull(.x, y) %>% 
               # this will regroup mtcars and diamonds in the list
               transpose() %>%
               # it can be transform in a two column tibble
               as_tibble()
  ) %>%
  ungroup()
#> # A tibble: 3 x 3
#>      id mtcars             diamonds          
#>   <int> <list>             <list>            
#> 1     1 <tibble [10 x 11]> <tibble [15 x 10]>
#> 2     2 <tibble [10 x 11]> <tibble [15 x 10]>
#> 3     3 <tibble [10 x 11]> <tibble [15 x 10]>

Created on 2019-02-20 by the reprex package (v0.2.1)

I let you dig into the details of how it works and tell us if there are questions.

2 Likes

Thanks. It works well.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.