为什么我不能在 R 中用 left_join 合并这两个文件?

Why I cannot merge the two files, with left_join, in R?

我正在尝试 link 在 R 中左连接的两个文件。我没有得到我需要的输出。

这里有两个文件的例子:

这里是file_1:

当我在 R 中执行 left_join 时,我没有得到我想要的。这是代码:

minap_piv_na_stemi_nstemi <- left_join(file_1, file_2)


                   

如您在最后一行中所见,Rochdale Infirmary 应填充 provider_nametrust_code。这不是发生了吗?有人可以帮忙吗?

试试这个。使用 left_join 通过 hospital_name 加入。使用例如coalesce 以填写 trust_codeprovider_name 的缺失信息。删除 .x.y 列:

library(dplyr)

left_join(file_1, file_2, by = "hospital_name") %>% 
  mutate(trust_code = coalesce(trust_code.x, trust_code.y),
         provider_name = coalesce(provider_name.x, provider_name.y)) %>% 
  select(-ends_with(".x"), -ends_with(".y"))
#> # A tibble: 182 x 3
#>    hospital_name           trust_code provider_name                             
#>    <chr>                   <chr>      <chr>                                     
#>  1 Addenbrooke's Hospital  RGT        Cambridge University Hospitals NHS Founda…
#>  2 Royal Albert Edward In… RRF        Wrightington, Wigan and Leigh NHS Foundat…
#>  3 Airedale General Hospi… RCF        Airedale NHS Trust                        
#>  4 Wycombe Hospital        RXQ        Buckinghamshire Healthcare NHS Trust      
#>  5 Barnsley Hospital       RFF        Barnsley Hospital NHS Foundation Trust    
#>  6 Basildon Hospital       RDD        Basildon and Thurrock University Hospital…
#>  7 Royal United Hospital … RD1        Royal United Hospital Bath NHS Trust      
#>  8 Bedford Hospital        RC1        Bedford Hospital NHS Trust                
#>  9 Broomfield Hospital     RQ8        Mid Essex Hospital Services NHS Trust     
#> 10 Rochdale Infirmary      RW6        Pennine Acute Hospitals NHS Trust         
#> # … with 172 more rows