3

Suppose I have two data frames, Dat1 and Dat2,

Dat1
Col1 Col2 Col3
A1    56   89

and

Dat2
Col1 Col2 Col4 Col5
A2   49    84   F11

Finally I want to have a combined data frame which looks like

Col1 Col2 Col3 Col4 Col5
A1    56   89   NA    NA
A2    49   NA   84    F11

Is it possible to achieve this in R?

Frank
  • 65,012
  • 8
  • 95
  • 173
darkage
  • 837
  • 3
  • 11
  • 21

2 Answers2

11

There's also rbind.fill from plyr or Stack.

library(plyr)

rbind.fill(Dat1, Dat2)

##   Col1 Col2 Col3 Col4 Col5
## 1   A1   56   89   NA <NA>
## 2   A2   49   NA   84  F11

library(Stack)

Stack(Dat1, Dat2)

##   Col1 Col2 Col3 Col4 Col5
## 1   A1   56   89   NA <NA>
## 2   A2   49   NA   84  F11
Jake Burkhead
  • 6,275
  • 2
  • 20
  • 32
5

You want to merge with all=TRUE:

merge(Dat1,Dat2,all=TRUE)
  Col1 Col2 Col3 Col4 Col5
1   A1   56   89   NA <NA>
2   A2   49   NA   84  F11

Col5 shows <NA> instead of NA because it is of mode factor

Matthew Lundberg
  • 41,139
  • 6
  • 86
  • 109