0

I have two data frames A and B, both with the same column col1.

Dataframe A:

col1<-c(1,2,3,4,5,)
col2<-c("a","a","a","b","b")
A<-data.frame(col1,col2)
A
col1 col2
1    a
2    a
3    a
4    b
5    b

Dataframe B:

col1<-c(1,3,4)
col2b<-c("a","b","b")
B<-data.frame(col1,col2)
B
col1 col2b
1    a
3    b
4    b
 

As you can see, data frame B is missing some values in col1 compared to data frame A. I would like to merge A and B using col1, and infill missing values in the B columns with NA (so, no recycling!). My desired output is something like this:

col1 col2 col2b
1    a     a
2    a  <NA>
3    a     b
4    b     b
5    b  <NA>

So far I've tried using cbind and cbind.na, with no luck. Any help or suggestions would be appreciated!

Cam
  • 449
  • 2
  • 7

1 Answers1

2

Use dplyr::left_join:

library(dplyr)

A %>% 
  left_join(B, by = c("col1"))
  col1 col2 col2b
1    1    a     a
2    2    a  <NA>
3    3    a     b
4    4    b     b
5    5    b  <NA>
BellmanEqn
  • 791
  • 3
  • 11