I guess my question might be unclear, so I try to clarify it. Suppose I have two data frames I want to merge. Each row in both data frames are unique companies. Both data frames also contain specific columns “id_1” and “id_2” with unique identifiers for these companies. I want them to join \ merge (data frames) using “id_1” and “id_2”. Minimum reproducible example id as follows:
x <- structure(list(company = c("Apple", "Amazon", "BMW", "Audi"),
id_1 = c("789879978", NA_character_, "12312312", NA_character_),
id_2 = c("32132131", "987978987", NA_character_, NA_character_)),
.Names = c("company", "id_1", "id_2"), row.names = c(1:4), class = "data.frame")
y <- structure(list(id_1 = c("789879978111", "987654000", "12312312", "111123231"),
id_2 = c("32132131", "987978987", "098099808908", "9999999991"),
region = c("USA", "USA", "EU", "EU")),
.Names = c("id_1", "id_2", "region"), row.names = c(1:4), class = "data.frame")
Desired output:
structure(list(company = c("Apple", "Amazon", "BMW", "Audi"),
id_1 = c("789879978", NA_character_, "12312312", NA_character_),
id_2 = c("32132131", "987978987", NA_character_, NA_character_),
region = c("USA", "USA", "EU", NA_character_)),
.Names = c("company", "id_1", "id_2", "region"), row.names = c(1:4), class = "data.frame")
As you might see for Apple “id_1” in “x” data frame is not the same than in “y” one, so I need to use “id_2” to merge these rows. Same for Amazon, while for BMW “id_2” in both data frames is NA so I can’t use “id_2”, so I need to use “id_1”. Suppose for some reason I can’t change/fix it. So that I need to use both “id_1” and “id_2” to merge data frames. The problem is that if I specify both columns as a keys in merge() and/or left_join() it would no work, since it requires a perfect match of values of both specified columns. In my case I need to use combination of “id_1” (if it is possible to match) or “id_2” (if I cant merge using “id_1”).
My questions is How can I merge two data frames using flexible condition, i.e. use “id_1” if it enough to merge and/or “id_2” if I can’t merge within “id_1”