rbind two data.frame preserving row order and row names

Alex picture Alex · Feb 10, 2013 · Viewed 16k times · Source

I have a list of data.frame objects which i would like to row append to one another, ie merge(..., all=T). However, merge seems to remove the row names which I need to be kept intact. Any ideas? Example:

x = data.frame(a=1:2, b=2:3, c=3:4, d=4:5, row.names=c("row_1", "another_row1"))
y = data.frame(a=c(10,20), b=c(20,30), c=c(30,40), row.names=c("row_2", "another_row2"))
> merge(x, y, all=T, sort=F)
     a  b  c  d
  1  1  2  3  4
  2  2  3  4  5
  3 10 20 30 NA
  4 20 30 40 NA

Answer

A5C1D2H2I1M1N2O1R2T1 picture A5C1D2H2I1M1N2O1R2T1 · Feb 10, 2013

Since you know you are not actually merging, but just rbind-ing, maybe something like this will work. It makes use of rbind.fill from "plyr". To use it, specify a list of the data.frames you want to rbind.

RBIND <- function(datalist) {
  require(plyr)
  temp <- rbind.fill(datalist)
  rownames(temp) <- unlist(lapply(datalist, row.names))
  temp
}
RBIND(list(x, y))
#               a  b  c  d
# row_1         1  2  3  4
# another_row1  2  3  4  5
# row_2        10 20 30 NA
# another_row2 20 30 40 NA