0

I got a problem when trying to merge two dataframes in R and I need your help. Suppose that I have following dataframes:

> Data_A
Code    year    score   
A       1991    1   
A       1992    2   
A       1993    3   
B       1991    3   
B       1993    7   
> Data_B
Code    year    l.score 
A       1991    NA  
A       1992    1   
A       1993    2   
A       1994    3   
B       1991    NA  
B       1992    3
B       1993    NA  
B       1994    7

And the desire result after merging them should be like that:

> Data_merge
    Code    year    score   l.score
    A      1991     1       NA
    A      1992     2       1
    A      1993     3       2
    B      1991     3       NA
    B      1993     7       NA

It means that when merging these dataframes, share columns in one will be kept (in this case, "Code" and "year" of Data_A). I tried merge(Data_A, Data_B, all = FALSE) but not success. Someone have any idea? Thanks for reading!

Sotos
  • 51,121
  • 6
  • 32
  • 66

2 Answers2

0
library(dplyr)
    Data_A %>%
    left_join(Data_B, by = c('Code', 'year'))

  Code year score l.score
1    A 1991     1      NA
2    A 1992     2       1
3    A 1993     3       2
4    B 1991     3      NA
5    B 1993     7      NA
AlexB
  • 3,061
  • 2
  • 17
  • 19
0

It seems your own solution can work (I am using R 3.6.1), but no idea why you cannot

> merge(Data_A, Data_B, all = FALSE)
  Code year score X1.score
1    A 1991     1       NA
2    A 1992     2        1
3    A 1993     3        2
4    B 1991     3       NA
5    B 1993     7       NA

DATA

Data_A <- structure(list(Code = structure(c(1L, 1L, 1L, 2L, 2L), .Label = c("A", 
"B"), class = "factor"), year = c(1991L, 1992L, 1993L, 1991L, 
1993L), score = c(1L, 2L, 3L, 3L, 7L)), class = "data.frame", row.names = c(NA, 
-5L))

Data_B <- structure(list(Code = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 
2L), .Label = c("A", "B"), class = "factor"), year = c(1991L, 
1992L, 1993L, 1994L, 1991L, 1992L, 1993L, 1994L), X1.score = c(NA, 
1L, 2L, 3L, NA, 3L, NA, 7L)), class = "data.frame", row.names = c(NA, 
-8L))
Sotos
  • 51,121
  • 6
  • 32
  • 66
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81