Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to expand the dplyr::tibble with the column contain list of list?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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]>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading