@RonakShah 今天早些时候发布了这个版本,但后来删除了它,因为他的解决方案不太符合要求。
想法是使用fuzzyjoin 包,它有很多功能可以在两个数据集之间进行模糊匹配。它们都不完全符合这个问题的要求,但这里有一个更长的答案应该这样做。
stringdist_inner_join 函数进行常规模糊匹配。它通过构造一个在fuzzy_join 中使用的复杂函数来工作。
它不导出该功能;但是您可以创建自己的函数(我称之为stringdist_match),它只创建函数并导出它。然后将其与比较第一个字母的组合,并使用 fuzzy_join 中的组合函数 (custom_match)。这是一些代码。 stringdist_match 的大部分函数都是从fuzzyjoin 包中复制而来的。
library(fuzzyjoin)
stringdist_match <- function(max_dist = 2,
method = c("osa", "lv", "dl", "hamming", "lcs", "qgram",
"cosine", "jaccard", "jw", "soundex"),
mode = "inner",
ignore_case = FALSE,
distance_col = NULL, ...) {
# It's a good idea to force evaluation of all the arguments
# in case they get changed between when we call this function and
# when we use the function it returns.
force(max_dist)
force(mode)
force(ignore_case)
force(distance_col)
forceotherargs <- list(...)
method <- match.arg(method)
if (method == "soundex") {
# soundex always returns 0 or 1, so any other max_dist would
# lead either to always matching or never matching
max_dist <- .5
}
function(v1, v2) {
if (ignore_case) {
v1 <- stringr::str_to_lower(v1)
v2 <- stringr::str_to_lower(v2)
}
# shortcut for Levenshtein-like methods: if the difference in
# string length is greater than the maximum string distance, the
# edit distance must be at least that large
# length is much faster to compute than string distance
if (method %in% c("osa", "lv", "dl")) {
length_diff <- abs(stringr::str_length(v1) - stringr::str_length(v2))
include <- length_diff <= max_dist
dists <- rep(NA, length(v1))
dists[include] <- stringdist::stringdist(v1[include], v2[include], method = method, ...)
} else {
# have to compute them all
dists <- stringdist::stringdist(v1, v2, method = method, ...)
}
ret <- tibble::tibble(include = (dists <= max_dist))
if (!is.null(distance_col)) {
ret[[distance_col]] <- dists
}
ret
}
}
# Now the example. First, create a matching function that
# just does the fuzzy part.
fuzzy_match <- stringdist_match()
# Next create a matching function that just compares first letters.
first_letter_match <- function(col1, col2)
sub("(^.).*", "\\1", col1) == sub("(^.).*", "\\1", col2)
# Now create one that requires both to match.
custom_match <- function(col1, col2)
first_letter_match(col1, col2) & fuzzy_match(col1, col2)
# Now run the example
df1 <- data.frame(name = c("Peter P", "Jim Gordon", "Bruce Wayne", "Tony Stark","Mony Blake" ))
df2<- data.frame(name = c( "Jeter P", "Bruce Wayne", "Mony Blake" ))
fuzzy_inner_join(df1, df2, by = "name", match_fun = custom_match)
#> name.x name.y
#> 1 Bruce Wayne Bruce Wayne
#> 2 Mony Blake Mony Blake
由reprex package (v0.3.0) 于 2020 年 2 月 21 日创建
有关stringdist_match 的所有参数的文档,请参阅?fuzzyjoin::stringdist_join。