Skip to content
Prev 374425 / 398513 Next

Converting a list to a data frame

Sometimes one want to "bind" list that have some columns in common and others that you want to include from one but leave as NA for the rows from the other. The rbind.list function from package-plyr is from the pre-tidy/tibble era of Hadley's efforts and provides that facility out of the box. It also seems to "work" with the do.call(rbind strategy for named lists above.

x <- list(A=mtcars[c("mpg", "wt")] , B=mtcars[c("wt", "cyl")])  #mtcars
x2 <- do.call(rbind.fill, lapply(names(x), function(z) 
     data.frame(type=z, x[[z]])))
str(x2)
#---------
'data.frame':	64 obs. of  4 variables:
 type: Factor w/ 2 levels "A","B": 1 1 1 1 1 1 1 1 1 1 ...
 mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
 wt  : num  2.62 2.88 2.32 3.21 3.44 ...
 cyl : num  NA NA NA NA NA NA NA NA NA NA ...