I\'m trying to combine a list of unequal data.frames; the obvious do.call(rbind, df.lst)
fails but the real problem is padding it out with NA
s.
Try
library(plyr)
ldply(df.lst,data.frame)
.id a b d e f g
1 A 1 5 2 1 1 1
2 A 2 4 3 1 2 2
3 B 1 3 2 NA NA NA
4 B 2 2 3 NA NA NA
5 C 1 4 1 1 NA NA
6 C 2 3 2 3 NA NA
If needed you can remove the first column :
df<-ldply(df.lst,data.frame)
df[,-1]
a b d e f g
1 1 5 2 1 1 1
2 2 4 3 1 2 2
3 1 3 2 NA NA NA
4 2 2 3 NA NA NA
5 1 4 1 1 NA NA
6 2 3 2 3 NA NA
If you want to stick with base R, you can do something like this:
### Get all the columns names
col <- unique(unlist(sapply(df.lst, names)))
col
## [1] "a" "b" "d" "e" "f" "g"
### Fill the missing columns with NA
df.lst <- lapply(df.lst, function(df) {
df[, setdiff(col, names(df))] <- NA
df
})
### Then Bind it
do.call(rbind, df.lst)
## a b d e f g
## A.1 1 5 2 1 1 1
## A.2 2 4 3 1 2 2
## B.1 1 3 2 NA NA NA
## B.2 2 2 3 NA NA NA
## C.1 1 4 1 1 NA NA
## C.2 2 3 2 3 NA NA
We can use
library(dplyr)
bind_rows(df.lst)
Or
library(data.table)
rbindlist(df.lst, fill=TRUE)