Guilherme Souza
Guilherme Souza

Reputation: 364

Convert nested lists to data.frame using all recursive indexes as colnames and fill missing columns with NAs

I have been struggling with this for a day now and all research made in SO doesn't seem to produce the result that i need.

I have this list:

    input_list <- list(
        list(A = 'a1', B = 'b1', C = 'c1', D = 'd1'),
        list(A = 'a2', C = 'c2', D = 'd2'),
        list(A = 'a3', B = 'b3', C = 'c3'),
        list(A = 'a4', B = 'b4', C = 'c4', 
             D = list(
                sub_1 = "d4_1",
                sub_2 = "d4_2")
             )
    )

Basically I want to turn it into this structure:

#tbl_df
#A  B  C  D  D.sub_1  D_sub_2
#a1 b1 c1 d1 NA       NA
#a2 NA c2 d2 NA       NA
#a3 b3 c3 NA NA       NA
#a4 b4 c4 NA d4_1     d4_2

I tried messing with map function:

output_list <- input_list %>% 
    map(unlist) %>% 
    do.call(rbind.data.frame, .)

It correctly unlists all nested lists converting them to named vectors, but I'm stuck as to how to rbind the rows matching the column names and fill missing variables with NAs.

Any help appreciated.

Upvotes: 0

Views: 287

Answers (3)

akrun
akrun

Reputation: 887911

We can use unnest_wider

library(purrr)
library(dplyr)
tibble(col = input_list) %>% 
     unnest_wider(c(col)) %>%
     unnest_wider(c(D))

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389315

You can use map_dfr :

purrr::map_dfr(input_list, as.data.frame)

#   A    B  C    D D.sub_1 D.sub_2
#1 a1   b1 c1   d1    <NA>    <NA>
#2 a2 <NA> c2   d2    <NA>    <NA>
#3 a3   b3 c3 <NA>    <NA>    <NA>
#4 a4   b4 c4 <NA>    d4_1    d4_2

Upvotes: 0

Duck
Duck

Reputation: 39613

Maybe try this. You can use unlist() with lapply() to unnest the values and then transform to dataframe each element using as.data.frame(t(...)). Finally, bind_rows() from dplyr can bind the elements as you expect. Here the code:

library(dplyr)
#Code
newdf <- bind_rows(lapply(input_list, function(x) as.data.frame(t(unlist(x)))))

Output:

   A    B  C    D D.sub_1 D.sub_2
1 a1   b1 c1   d1    <NA>    <NA>
2 a2 <NA> c2   d2    <NA>    <NA>
3 a3   b3 c3 <NA>    <NA>    <NA>
4 a4   b4 c4 <NA>    d4_1    d4_2

Upvotes: 1

Related Questions