Home > Software engineering >  how to expand the dplyr::tibble with the column contain list of list?
how to expand the dplyr::tibble with the column contain list of list?

Time:12-18

Here is what I have and what I want:

what_i_have <- dplyr::tibble(
    col_str = "abc",
    col_int = 1,
    col_ls = list(list(
        c(l1 = "1", l2 = "3", l3 = "5"),
        c(l1 = "2", l2 = "4", l3 = "6")
    ))
)

what_i_want <- dplyr::tibble(
    col_str = "abc",
    col_int = 1,
    col_ls = list(
        c(l1 = "1", l2 = "3", l3 = "5"),
        c(l1 = "2", l2 = "4", l3 = "6")
    )
)

what_i_have looks like this

r$> what_i_have                                             
# A tibble: 1 × 3
  col_str col_int col_ls    
  <chr>     <dbl> <list>    
1 abc           1 <list [2]>

what_i_want looks like this

r$> what_i_want                                             
# A tibble: 2 × 3
  col_str col_int col_ls   
  <chr>     <dbl> <list>   
1 abc           1 <chr [3]>
2 abc           1 <chr [3]>

How to turn what_i_have to what_i_want? Thank you.

CodePudding user response:

We could use unnest from tidyr package:

library(tidyr)
library(dplyr)

what_i_have %>% 
  unnest(cols = c(col_ls))
  col_str col_int col_ls   
  <chr>     <dbl> <list>   
1 abc           1 <chr [3]>
2 abc           1 <chr [3]>
  • Related