martinkabe martinkabe -3 years ago 124
R Question

Stacking list column in data frame

I have the following data frame with list column:

a <- data.frame(col1=c("a","b","c"))
a$col2 <- list(list(),list(name="Michal", age=28), list(name="Johnny", age=31))

I'd like to merge these columns together as a data frame so the desired output would look like below data frame:

col1 name age
1 a NA NA
2 b Michal 28
3 c Johny 31

For transforming list column into data frame I'm using

plyr::ldply(a$col2, data.frame)
lapply(a$col2, data.frame, stringsAsFactors = FALSE)

but unfortunately it'll skip empty list in first position:

name age
1 Michal 28
2 Johny 31

Is there any trick, how to keep this empty list for further cbind().

Answer Source

Here is one option with data.table

setDT(a)[, unlist(col2, recursive = FALSE), col1][a[, "col1", with = FALSE], on = .(col1)]
#   col1   name age
#1:    a     NA  NA
#2:    b Michal  28
#3:    c Johnny  31

If we need a tidyverse option

a$col2 %>% 
    set_names(a$col1) %>% 
    Filter(length, .) %>% 
    bind_rows(., .id = "col1") %>% 
    left_join(a[1], .)
#   col1   name age
#1    a   <NA>  NA
#2    b Michal  28
#3    c Johnny  31
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download