[R] rbind with missing columns

Duncan Murdoch dmurdoch at pair.com
Fri Apr 30 14:15:18 CEST 2004


On Fri, 30 Apr 2004 13:47:35 +0200, <klaus.thul at infineon.com> wrote :

>Hello,
>
>I have several data sets, which I want to combine column-by-column using
>"rbind" (the data sets have ~100 columns). The problem is, that in some
>data sets some of the columns are missing.
>
>Simply using rbind gives me:
>"Error in match.names(clabs, names(xi)) : names don't match previous
>names"
>
>Is there a simple way to make R do the rbind despite the missing columns
>and to fill out the missing data with NA's? (I could program this
>somehow, but probably there is one very simple solution available)

It's not there already as far as I know, but it's not too hard to
write a new rbind that does this:

newrbind <- function(A,B) {
  anames <- names(A)
  bnames <- names(B)
  notinb <- anames[!(anames %in% bnames)]
  if (length(notinb)) B[[notinb]] <- rep(NA, nrow(B))
  notina <- bnames[!(bnames %in% anames)]
  if (length(notina)) A[[notina]] <- rep(NA, nrow(A))
  rbind(A, B)
}

This only works on data.frames; if you want it to work as generally as
the real rbind, you'll need to add some extra conversions at the
start.

Duncan Murdoch




More information about the R-help mailing list