![](/img/trans.png)
[英]How to use left join in tidyverse package only match the first one with multiple different variables in two dfs?
[英]How to left join multiple DFs in R with different ID name
我在谷歌驅動器上有 15 個 CSV,我想下載它們並同時加入它們。 十三個具有相同的 ID 變量 (inegi),但兩個具有不同的 ID 名稱(CVEGEO 和 id_mun)。 如何在列中加入其他兩個具有不同 ID 名稱的? 這是我目前擁有的代碼:
# Paquetes ---------------------------------------------------------------
if(!require(pacman)) install.packages("pacman")
pacman::p_load(tidyverse, janitor, googledrive,
stringr, purrr)
# Download municipal Files -------------------------------------------------------------------
files_municipal <- drive_ls(as_id("IDOFGOOGLE")) %>%
filter(!str_detect(name, "cumulative-deaths|excess")) %>%
arrange(name)
tmp <- paste(tempdir(), files_municipal$name, sep = "/")
walk2(files_municipal$id, tmp, ~ drive_download(as_id(.x), path = .y, overwrite = TRUE))
# Join --------------------------------------------------------------------
tempo <- map(tmp, read_csv) %>%
reduce(left_join, by = "inegi")
我有解決辦法。 我在開始時創建了一個函數:
# Paquetes ---------------------------------------------------------------
if(!require(pacman)) install.packages("pacman")
pacman::p_load(tidyverse, janitor, googledrive,
stringr, purrr)
# Functions ---------------------------------------------------------------
read_vars_mun <- function(df) {
df <- read_csv(df) %>%
rename_with(
~ case_when(
. == "CVEGEO" ~ "inegi",
. == "id_mun" ~ "inegi",
TRUE ~ .)) %>%
mutate(inegi = as.character(inegi))
}
# Download municipal Files -------------------------------------------------------------------
files_municipal <- drive_ls(as_id("IDOFGOOGLE")) %>%
filter(!str_detect(name, "cumulative-deaths|excess")) %>%
arrange(name)
tmp <- paste(tempdir(), files_municipal$name, sep = "/")
walk2(files_municipal$id, tmp, ~ drive_download(as_id(.x), path = .y, overwrite = TRUE))
# Join --------------------------------------------------------------------
df <- map(tmp, read_vars_mun) %>%
reduce(left_join, by = "inegi")
# Done.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.