unnest into several columns

I have a tibble, that has a list-column. Each entry of this list-column is itself a list of several named elements (always the same number and name). I wish to unpack it into their own columns.

The objects in the individual list can be complex, so I expect the resulting expanded columns to be themselves list-columns.

Here is an example, using matrices to illustrate (the content of the matrices is irrelevant here):

library(tidyverse)

tib <- tibble(id = 1:3,
              data_col = map(1:3,
                             ~ list(A = matrix(.x, nrow = .x, ncol = .x),
                                    B = matrix(.x + 1, nrow = .x, ncol = .x),
                                    C = as.character(.x))))

tib
#> # A tibble: 3 × 2
#>      id data_col        
#>   <int> <list>          
#> 1     1 <named list [3]>
#> 2     2 <named list [3]>
#> 3     3 <named list [3]>

I can get the result I want with this unwieldy approach:

tib |>
  unnest(data_col) |>
  mutate(data_type = names(data_col)) |>
  pivot_wider(id_cols = id,
              names_from = data_type,
              values_from = data_col)
#> # A tibble: 3 × 4
#>      id A             B             C           
#>   <int> <named list>  <named list>  <named list>
#> 1     1 <int [1 × 1]> <dbl [1 × 1]> <chr [1]>   
#> 2     2 <int [2 × 2]> <dbl [2 × 2]> <chr [1]>   
#> 3     3 <int [3 × 3]> <dbl [3 × 3]> <chr [1]>

Created on 2023-08-23 with reprex v2.0.2

I think I'm missing some more obvious approach.

And indeed, there was a much more obvious solution: unnest_wider(), I had forgotten this exists.

unnest_wider(tib,col = data_col)
#> # A tibble: 3 × 4
#>      id A             B             C    
#>   <int> <list>        <list>        <chr>
#> 1     1 <int [1 × 1]> <dbl [1 × 1]> 1    
#> 2     2 <int [2 × 2]> <dbl [2 × 2]> 2    
#> 3     3 <int [3 × 3]> <dbl [3 × 3]> 3

Created on 2023-08-23 with reprex v2.0.2

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.