首页 > 解决方案 > 按模式反连接

问题描述

TibbleA包含可能在 tibble 中找到的键/模式B。我的目标是识别在 tibble 中找不到的键/模式B

我想通过匹配模式反连接两个表:

A <- tibble( colA = c("B12", "B19", "B202", "B87", "B61", "B55") )
B <- tibble( colB = c("aaB87aa", "bbbbB55", "B202cccc") )

我发现该功能fuzzyjoin应该可以工作,但我无法正确使用它:

test <- regex_anti_join(A, B, by = c(colB = "colA"))

编辑

最后我想要这样的东西:

test
1 B12
2 B19
3 B61

标签: rregexdplyrfuzzyjoin

解决方案


regex_anti_join(A, B, by = c(colA = colB))执行 a str_detectof colBinside colA。在您的情况下,这不返回任何内容,因此结果为空。

你需要做相反的事情:colA在里面搜索colB

这可以通过将匹配函数指定给以下fuzzy_join函数使用的函数来实现regex_anti_join

library(fuzzyjoin)

# This is exactly the inverse of the match_fun used inside regex_anti_join
match_fun <- function(v1, v2) {
  stringr::str_detect(v2, stringr::regex(v1))
}

fuzzy_join(A, B, by = c("colA" = "colB"), match_fun=match_fun, mode = 'anti')
#> # A tibble: 3 x 1
#>   colA 
#>   <chr>
#> 1 B12  
#> 2 B19  
#> 3 B61

reprex 包于 2020-07-17 创建(v0.3.0)


推荐阅读