The procedure is the same for any number of keys. You need a column in each table that has no NA
s(missing values). (Edit: If no such column exists in one of the tables, the you can create a dummy column like so: dfa$dummy1 <-1
)
After the merge, these columns will contain NA
s if that row doesn't have a match in the other table. Then you can just search for these rows in the merged table, and assign the appropriate flags:
set.seed(123)
dfa <- data.frame(id=c(1,2,3,5),val1=rnorm(4))
dfa
#> id val1
#> 1 1 -0.56047565
#> 2 2 -0.23017749
#> 3 3 1.55870831
#> 4 5 0.07050839
dfb <- data.frame(id=c(1,2,4,5),val2=rnorm(4))
dfb
#> id val2
#> 1 1 0.1292877
#> 2 2 1.7150650
#> 3 4 0.4609162
#> 4 5 -1.2650612
dfc <- merge(dfa,dfb,all=T)
dfc$flag <- 3 # Assume all rows are matched by default
dfc$flag[is.na(dfc$val1)] <- 1 # Search for NAs in val1 for no-match due to dfA
dfc$flag[is.na(dfc$val2)] <- 2 # Search for NAs in val2 for no-match due to dfB
dfc
#> id val1 val2 flag
#> 1 1 -0.56047565 0.1292877 3
#> 2 2 -0.23017749 1.7150650 3
#> 3 3 1.55870831 NA 2
#> 4 4 NA 0.4609162 1
#> 5 5 0.07050839 -1.2650612 3
Created on 2020-01-13 by the reprex package (v0.3.0)