R-通过levenshtein距离返回n个匹配项

时间:2018-11-02 21:21:28

标签: r dataframe tm levenshtein-distance stringdist

我想通过levenshtein距离找到与给定字符串的n个最佳匹配。我知道R中的adist函数提供了最小的距离,但是我试图将结果的数量缩放到10。例如,下面有一些代码。

name <- c("holiday inn", "geico", "zgf", "morton phillips")
address <- c("400 lafayette pl tupelo ms", "227 geico plaza chevy chase md", 
     "811 quincy st washington dc", "1911 1st st rockville md")

source1 <- data.frame(name, address)

name <- c("williams sonoma", "mamas bbq", "davis polk", "hop a long diner",
  "joes crag shack", "mike lowry place", "holiday inn", "zummer")

name2 <- c(NA, NA, NA, NA, NA, NA, "hi express", "zummer gunsul frasca")
address <- c("2 reads way new castle de", "248 w 4th st newark de",
     "1100 21st st nw washington dc", "1804 w 5th st wilmington de",
     "1208 kenwood parkway holdridge nb", "4203 ocean drive miami fl",
     "400 lafayette pl tupelo ms", "811 quincy st washington dc")
source2 <- data.frame(name, name2, address)

dist.mat.nm <- adist(source1$name, source2$name, partial = T, ignore.case = TRUE)

dist.mat.ad <- adist(source1$address.full, source2$address.full, partial = TRUE, ignore.case = TRUE)
dist.mat <- ifelse(is.na(dist.mat.nm), dist.mat.ad, dist.mat.nm)
dist.mat2 <- ifelse(is.na(dist.mat.ad), dist.mat.nm, dist.mat.ad)
which.match <- function(x, nm) return(nm[which(x == min(x))[1]])
which.index <- function(x, nm) return(which(x == min(x))[1])

source2.matches.name <- apply(dist.mat, 1, which.match, nm = source2$name)
source2.name.index <- apply(dist.mat, 1, which.index, nm = 
source2$names[source2.matches.name])

期望的结果是一个数据帧,其中包含source1$name,以及使用adist并根据source1$address及其最佳5个匹配项的基于距离的最佳5个匹配项的列。也许是使用top_n中的dplyr的东西?如果不清楚,请告诉我。任何帮助深表感谢。谢谢。

1 个答案:

答案 0 :(得分:1)

如果我理解这个问题,那么您可以根据需要进行操作。
首先,我将重新运行创建dist.mat.ad的代码行,因为您的代码有错误,当它们被命名为address.full时,它引用了列address

dist.mat.ad <- adist(source1$address, source2$address, partial = TRUE, ignore.case = TRUE)

现在想要的结果。

imat <- apply(dist.mat.nm, 1, order)[1:5, ]
top.nm <- data.frame(name = source1$name)
tmp <- apply(imat, 1, function(i) source2$name[i])
colnames(tmp) <- paste("top", 1:5, sep = ".")
top.nm <- cbind(top.nm, tmp)

imat <- apply(dist.mat.ad, 1, order)[1:5, ]
top.ad <- data.frame(address = source1$address)
tmp <- apply(imat, 1, function(i) source2$address[i])
colnames(tmp) <- paste("top", 1:5, sep = ".")
top.ad <- cbind(top.ad, tmp)

结果在top.nmtop.ad中。
最终清理。

rm(imat, tmp)