Unnest multiple columns-list from tibble with tidyr unnes_wider

Viewed 332

This is my tibble:

my_tibble<-tibble(Level = list(c(10,20),c(10,20)),Level2 = list(c(30,40),c(50,20)),Level3 = list(c(330,430),c(530,33)))

I want to unnest using unnest_wider all columns: Level,Level2,Level3.

I am doing this: unnest_wider(my_tibble,Level,Level2,Level3) and of course is not working.

How can I do this?

2 Answers

Perhaps similarly to the answer above using map but with easier naming.

map_dfc(colnames(my_tibble), 
        ~ unnest_wider(my_tibble[.x], .x, names_sep = "."))

We could use unlist2d with map

library(purrr)
library(collapse)
map_dfc(my_tibble, ~ unlist2d(.x) %>% 
        select(-1)) %>%
     set_names(paste0(rep(names(my_tibble), each = 2), "_", 1:2))

-output

#    Level_1 Level_2 Level2_1 Level2_2 Level3_1 Level3_2
#1      10      20       30       40      330      430
#2      10      20       50       20      530       33

Or loop over the names of the data in map and apply unnest_wider

library(tidyr)
map_dfc(names(my_tibble), 
     ~ my_tibble %>% 
          select(.x) %>%
         unnest_wider(.x)) %>%
  set_names(paste0(rep(names(my_tibble), each = 2), "_", 1:2))

According to documentation from ?unnest_wider

.col, col - List-column to extract components from.

So, it is just a single column that we can specify where as in ?unnest, it is cols

cols - Columns to unnest.

Related