[R] rbind with missing columns

Michael Dewey m.dewey at iop.kcl.ac.uk
Sun May 2 12:24:07 CEST 2004


At 11:03 01/05/04, you wrote:
>Message: 3
>Date: Fri, 30 Apr 2004 13:47:35 +0200
>From: <klaus.thul at infineon.com>
>Subject: [R] rbind with missing columns
>To: <r-help at stat.math.ethz.ch>
>Message-ID:
>         <7509DD89A305F34E9EF16F1EEDFB80AF08D6D3 at drsse401.eu.infineon.com>
>Content-Type: text/plain;       charset="us-ascii"
>
>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)
>
>To make it clear here a simplified example. "unknown.command" is what I
>am looking for.
>
>A <- data.frame(a = c(1,2,3), b = c(4,5,6))
>B <- data.frame(a = c(1,2,3))
>unknown.command(A, B) - should give
>
>A B
>1 4
>2 5
>3 6
>4 NA
>5 NA
>6 NA

Does

A$id <- 1:nrow(A)
B$id <- 1:nrow(B) + nrow(A)
AandB <- merge(A, B, all = TRUE)


 > A
   a b id
1 1 4  1
2 2 5  2
3 3 6  3
 > B
   a id
1 1  4
2 2  5
3 3  6
 > AandB
   a id  b
1 1  1 4
2 1  4 NA
3 2  2 5
4 2  5 NA
5 3  3 6
6 3  6 NA
 >

Give you what you wanted? You can always strip out the "id" column if you 
wish (after sorting on it if you would like the original order back.

>Thank you for your help
>Klaus

Michael Dewey
m.dewey at iop.kcl.ac.uk




More information about the R-help mailing list