4

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
  • 66,179
  • 8
  • 96
  • 180
darkage
  • 857
  • 3
  • 12
  • 22

2 Answers2

12

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,435
  • 2
  • 21
  • 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
  • 42,009
  • 6
  • 90
  • 112