fsmart fsmart - 2 months ago 8
R Question

R: Stacking mismatched data.frames

I would like to stack vertically two data frames that do not match in variables. For the variables that do not appear in one of the data frames, I would like the variables to be filled in with whatever missing values are appropriate

NA
or
""
as the case may be. I would program something myself but I hate to reinvent the wheel if someone already has programmed this tool.

A <- data.frame(a=1:10, b=rnorm(10), c=rnorm(10))
B <- data.frame(a=1:10, c=rnorm(10), d=rnorm(10))

Answer

You can use rbindlist after keeping the data.frames in a list

library(data.table)#v1.9.5+
rbindlist(list(A,B), fill=TRUE)

Or

library(dplyr)
bind_rows(A,B)

Or

library(plyr)
rbind.fill(A, B)
Comments