Unnest multiple nested dataframes in R

Viewed 434

I am looking for a way to unnest a nested list with dataframes. The challenge is that I have to do unnest_wider() first and unnest() next, and both of them can only take one column at the time. I have to do over 30 columns and each of them contains a nested dataframes.

This is the replicate case that looks similar to my dataframe.

df <- tibble(
  character = c("Toothless", "Dory"),
  metadata = list(
    list(
      species = "dragon",
      color = "black",
      films = c(
        "How to Train Your Dragon",
        "How to Train Your Dragon 2",
        "How to Train Your Dragon: The Hidden World"
      )
    ),
    list(
      species = "blue tang",
      color = "blue",
      films = c("Finding Nemo", "Finding Dory")
    )
  )
)
df$mtcars <- list(mtcars)
df$iris <- list(iris)
df$longley <- list(longley)

My current working

df1 <- df %>% 
  unnest_wider(mtcars, names_sep = "_") %>% 
  unnest_wider(iris, names_sep = "_") %>%
  unnest_wider(longley, names_sep = "_")

df2 <- df1 %>% 
  unnest(mtcars_mpg) %>% 
  unnest(mtcars_cyl) %>% 
  unnest(mtcars_disp)

Any advice to do it efficiently will be highly appreciated.

0 Answers
Related