r-通过列表中的名称将left_join映射到许多匹配的表



当有多个表相互关联时,如何联接表?

在这个例子中,我有两组表。我试图将2021年的表格总数添加到2022年的表格中,作为一个名为2021的新列。4年前,我有100多套这样的桌子。因此,我寻找一种通过表名列表映射(或循环(left_joins(或cbind或其他什么(的可能性。这是我天真的尝试:

library(dplyr)
# Table 1 from 2022
T1 <- tibble(Variable = c("DS", "SR", "TI", "Total"), 
Total = c("71%", "24%", "5%", "100%"))
T1
# Table 1 from 2021
T1_2021 <- tibble(Variable = c("DS", "SR", "TI", "Total"), 
Total = c("40%", "40%", "20%", "100%"))
T1_2021
# here I simple left_join the T1 and T1_2021 to apply the Total from 2021 to a new column '2021' into T_2022_2021 (works)
T1_2022_and_total_of_2021 <- left_join(T1, T1_2021 %>% 
select(Variable, Total) %>%
rename('2021' = Total),
by = "Variable") 
T1_2022_and_total_of_2021
# other related tables
## Table 2 from 2022
T2 <- tibble(Variable = c("m", "f", "Total"), 
Total = c("45", "55%", "100%"))
## Table 2 from 2021
T2_2021 <- tibble(Variable = c("m", "f", "Total"), 
Total = c("48%", "52%", "100%"))
# then I have a List with the names of my tables from 2022 (in real more than 100)
tab_list <- list("T1", "T2")
# then I try to map the left_joins for every table from 2021 to the equivalent table from 2022 (T1, T2)
map(tab_list, ~left_join(.x, paste0(.x, "_2021") %>% 
select(Variable, Total) %>%
rename('2021' = Total),
by = "Variable"))

我怎样才能让它发挥作用?

我们需要对象的值。使用getmget(用于多个元素(

library(purrr)
library(dplyr)
map(tab_list, ~left_join(get(.x), get(paste0(.x, "_2021")) %>% 
select(Variable, Total) %>%
rename('2021' = Total),
by = "Variable"))

-输出

[[1]]
# A tibble: 4 × 3
Variable Total `2021`
<chr>    <chr> <chr> 
1 DS       71%   40%   
2 SR       24%   40%   
3 TI       5%    20%   
4 Total    100%  100%  
[[2]]
# A tibble: 3 × 3
Variable Total `2021`
<chr>    <chr> <chr> 
1 m        45    48%   
2 f        55%   52%   
3 Total    100%  100%  

最新更新