Given three data frames:
df1 <- data.frame(
id = c(1:3),
ctry1 = c("us", "es", "fr"),
ctry2 = c("ve", "pa", "us"),
ctry3 = c("co", "co", "es")
)
df2 <- data.frame(
id = c(1:3),
ctry1 = c("ve", "ve", "us"),
ctry2 = c("es", "pa", "us"),
ctry3 = c("pa", "co", "es")
)
iso <- data.frame(
ctry = c("us", "es", "fr", "ve", "pa", "ar", "co"),
iso_ctry = c("840", "724", "250", "862", "591", "032", "170")
)
** How can I join the variable iso_ctry from the iso data frame with all three columns of the df1 and df2 data frames?**
It works with the following function and map() from purrr, but I suspect there should be a faster way. Perhaps with a loop or a two arguments function.
join_iso <- function(df) {
left_join(df, iso, by = c("ctry1" = "ctry")) %>%
left_join(iso, by = c("ctry2" = "ctry")) %>%
left_join(iso, by = c("ctry3" = "ctry")) %>%
rename(iso_ctry1 = iso_ctry.x, iso_ctry2 = iso_ctry.y, iso_ctry3 = iso_ctry)
}
df_list <- list(df1, df2)
(df1_new <- map(df_list, join_iso))
question from:
https://stackoverflow.com/questions/65906682/joining-multiple-dataframes-by-different-columns-using-a-function-and-map-in-r 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…