与 R 的模糊 LEFT 连接

Jas*_*ter 3 join r dplyr fuzzyjoin

library(tidyverse)
library(fuzzyjoin)

df1 <- tibble(col1 = c("apple", "banana", "carrot"),
              col2 = as.numeric(0:2),
              col3 = as.numeric(0:2))
#> # A tibble: 3 x 3
#>   col1   col2  col3
#>   <chr> <int> <int>
#> 1 apple     0     0
#> 2 banana    1     1
#> 3 carrot    2     2

df2 <- tibble(col4 = c("app", "carr"), col5 = c(5, 9), matched = rep(TRUE, 2))
#> # A tibble: 2 x 3
#>   col4   col5 matched
#>   <chr> <dbl> <lgl>  
#> 1 app       5 TRUE   
#> 2 carr      9 TRUE 
Run Code Online (Sandbox Code Playgroud)

我上面有两个数据框df1df2我需要创建一个新列来df1告诉每一行是否与 中的条目匹配df2

我还必须进行模糊匹配,并且模糊性需要不区分大小写(因此是自定义ci_str_detect函数):

ci_str_detect <- function(x, y){str_detect(x, regex(y, ignore_case = TRUE))}

df1 %>% 
  fuzzy_inner_join(df2, by = c("col1" = "col4"), match_fun = ci_str_detect)
#># A tibble: 2 x 6
#>  col1    col2  col3 col4   col5 matched
#>  <chr>  <dbl> <dbl> <chr> <dbl> <lgl>  
#>1 apple      0     0 app       5 TRUE   
#>2 carrot     2     2 carr      9 TRUE 
Run Code Online (Sandbox Code Playgroud)

不幸的是(在这种情况下)fuzzyjoin R 包似乎只执行 INNER JOIN,而不是我需要的 LEFT JOIN。

最终我需要这个输出:

#> # A tibble: 3 x 6
#>   col1    col2  col3 col4   col5  matched
#>   <chr>  <dbl> <dbl> <chr> <dbl>  <lgl>  
#> 1 apple      0     0 app       5  TRUE   
#> 2 banana     1     1 NA       NA  FALSE 
#> 3 carrot     2     2 carr      9  TRUE 
Run Code Online (Sandbox Code Playgroud)

...并且 LEFT JOIN 将提供如下所示的中间数据帧,我可以替换它NAFALSE获得我最终想要的内容(直接在上面)。

#> # A tibble: 3 x 6
#>   col1    col2  col3 col4   col5  matched
#>   <chr>  <dbl> <dbl> <chr> <dbl>  <lgl>  
#> 1 apple      0     0 app       5  TRUE   
#> 2 banana     1     1 NA       NA  NA 
#> 3 carrot     2     2 carr      9  TRUE 
Run Code Online (Sandbox Code Playgroud)

如何在 R 中模糊 LEFT join?

bio*_*iha 7

瞧:)

fuzzy_left_join(df1, df2, match_fun = ci_str_detect, by = c(col1 = "col4"))
Run Code Online (Sandbox Code Playgroud)

  • tangent - 你知道为什么 `"col1"` 或 `col1` 可以在上面工作吗?同样的原因 `library(dplyr)` 或 `library("dplyr")` 会起作用吗? (2认同)