Inner_join 基于 R 中不同名称的多列的多个数据框

Inner_join multiple data frames based on multiple columns with different names in R

我有两个这样的数据框

library(tidyverse)

df1 <- tibble(.x=c(334,335,395),
              .y=c(574,600,466))

df1
#> # A tibble: 3 × 2
#>      .x    .y
#>   <dbl> <dbl>
#> 1   334   574
#> 2   335   600
#> 3   395   466


df2 <- tibble(id=c(334,335,395,466,574,600),
              fruits=c("apple","banana","ananas","pear","cherry","orange"))

df2
#> # A tibble: 6 × 2
#>      id fruits
#>   <dbl> <chr> 
#> 1   334 apple 
#> 2   335 banana
#> 3   395 ananas
#> 4   466 pear  
#> 5   574 cherry
#> 6   600 orange

reprex package (v2.0.1)

创建于 2022-03-02

每个水果都有一个 id,如 df2 中所示。 df1 有这些水果的代码。我想加入 df1 和 df2,我的数据如下所示

.x   .y    fruits.x  fruits.y
334. 574    apple     cherry
335  600    banana    orange
395  466    ananas    pear

我可以使用 inner_join 两次不同的时间然后绑定 data.frames 但我是 想知道我是否缺少一种优雅的方式

感谢您的宝贵时间

你可能想要的是match

library(tidyverse)
df1 %>%
  mutate(across(everything(), ~df2$fruits[match(., df2$id)]))

# A tibble: 3 x 2
  .x     .y    
  <chr>  <chr> 
1 apple  cherry
2 banana orange
3 ananas pear 

如果您想将此信息添加到您的 df1 而不是替换它,请检查 across 中的 .names 参数。


添加列的解决方案:

df1 %>%
  mutate(across(everything(), ~df2$fruits[match(., df2$id)], .names = "{.col}_fruits"))

# A tibble: 3 x 4
     .x    .y .x_fruits .y_fruits
  <dbl> <dbl> <chr>     <chr>    
1   334   574 apple     cherry   
2   335   600 banana    orange   
3   395   466 ananas    pear