agrep:只返回最佳匹配

发布于 2024-11-02 15:10:57 字数 661 浏览 0 评论 0原文

我在 R 中使用“agrep”函数,它返回匹配向量。我想要一个类似于 agrep 的函数,它只返回最佳匹配,或者如果存在平局则返回最佳匹配。目前,我正在对结果向量的每个元素使用“cba”包中的“sdist()”函数来执行此操作,但这似乎非常多余。

/edit:这是我当前正在使用的功能。我想加快速度,因为计算两次距离似乎是多余的。

library(cba)
word <- 'test'
words <- c('Teest','teeeest','New York City','yeast','text','Test')
ClosestMatch <- function(string,StringVector) {
  matches <- agrep(string,StringVector,value=TRUE)
  distance <- sdists(string,matches,method = "ow",weight = c(1, 0, 2))
  matches <- data.frame(matches,as.numeric(distance))
  matches <- subset(matches,distance==min(distance))
  as.character(matches$matches)
}

ClosestMatch(word,words)

I'm using the 'agrep' function in R, which returns a vector of matches. I would like a function similar to agrep that only returns the best match, or best matches if there are ties. Currently, I am doing this using the 'sdist()' function from the package 'cba' on each element of the resulting vector, but this seems very redundant.

/edit: here is the function I'm currently using. I'd like to speed it up, as it seems redundant to calculate distance twice.

library(cba)
word <- 'test'
words <- c('Teest','teeeest','New York City','yeast','text','Test')
ClosestMatch <- function(string,StringVector) {
  matches <- agrep(string,StringVector,value=TRUE)
  distance <- sdists(string,matches,method = "ow",weight = c(1, 0, 2))
  matches <- data.frame(matches,as.numeric(distance))
  matches <- subset(matches,distance==min(distance))
  as.character(matches$matches)
}

ClosestMatch(word,words)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

抱着落日 2024-11-09 15:10:57

agrep 包使用 Levenshtein Distances 来匹配字符串。 RecordLinkage 包有一个 C 函数来计算 Levenshtein 距离,可以直接使用它来加速计算。这是一个重新设计的 ClosestMatch 函数,速度提高了大约 10 倍

library(RecordLinkage)

ClosestMatch2 = function(string, stringVector){

  distance = levenshteinSim(string, stringVector);
  stringVector[distance == max(distance)]

}

The agrep package uses Levenshtein Distances to match strings. The package RecordLinkage has a C function to calculate the Levenshtein Distance, which can be used directly to speed up your computation. Here is a reworked ClosestMatch function that is around 10x faster

library(RecordLinkage)

ClosestMatch2 = function(string, stringVector){

  distance = levenshteinSim(string, stringVector);
  stringVector[distance == max(distance)]

}
青巷忧颜 2024-11-09 15:10:57

RecordLinkage 包已从 CRAN 中删除,请使用 stringdist 代替:

library(stringdist)

ClosestMatch2 = function(string, stringVector){

  stringVector[amatch(string, stringVector, maxDist=Inf)]

}

RecordLinkage package was removed from CRAN, use stringdist instead:

library(stringdist)

ClosestMatch2 = function(string, stringVector){

  stringVector[amatch(string, stringVector, maxDist=Inf)]

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文