Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rbind a list of data frames with different columns [duplicate]

Tags:

r

I have a list of data frames where some data frames have less columns. See example:

a <- data.frame (x1 = 1, x3 = 2, x4 = 7)
b <- data.frame (x1 = 3, x2 = 4, x3 = 3, x4 = 8)
c <- data.frame (x1 = 9, x2 = 5, x3 = 2, x4 = 9)
myList = list(a, b, c)

data frame a misses column x2. I need to have a data frame out of myList, so I do the following:

mydf = do.call(rbind, myList)

But the problem is that I get the following error:

Error in rbind(deparse.level, ...) : 
  numbers of columns of arguments do not match

How can I get a data frame where column x2 for a is filled with NA?

like image 634
Bruno Guarita Avatar asked Nov 19 '17 15:11

Bruno Guarita


1 Answers

You can use data.table:

library(data.table)
rbindlist(myList, fill = TRUE)
#   x1 x3 x4 x2
#1:  1  2  7 NA
#2:  3  3  8  4
#3:  9  2  9  5
like image 161
LyzandeR Avatar answered Nov 15 '22 00:11

LyzandeR