How can I convert a list of data frames into a data frame of lists using purrr or tidyr?

Viewed 535

This question seems like it has probably been answered before, but I have not found anything exactly on point. I have a list of data frames, which I would like to convert to a data frame with two columns -- ID and data. ID should be a column of integers, and data should be a column of data frames. Here's a toy example of the list of data frames that I would like to convert to a single data frame with two rows (one for each unique ID) and two columns (ID and data):

library(tidyverse)
library(purrr)

list <- list(tibble(ID = rep(1, 4),
                    a = c(1, 2, 3, 4), 
                    b = c(4, 3, 2, 1)),
             tibble(ID = rep(2, 3),
                    c = c(4, 5, 6),
                    d = c(6, 5, 4))
           )

This seems like a job for tidyr::unnest, but my effort to use that function was unsuccessful:

df <- unnest(list, cols = ID)
#> Error in UseMethod("unnest") : 
#>  no applicable method for 'unnest' applied to an object of class "list"

I was also unable to accomplish my goal using tibble:

df <- tibble(list, .rows = ID)
#> Error in tibble_quos(xs[!is.null], .rows, .name_repair) : 
#>  object 'ID' not found

How can I convert my list of data frames into a data frame of lists, ideally using purrr or tidyr?

1 Answers

If I understand the output you want correctly, you can do

list %>% map_df(~.x %>% nest(cols=-ID))

Since nest requires a data.frame, you need to map over the data frames in the list to do the mapping. Then map_df will combine everything into one data.frame in the end.

Related