agrep:只返回最佳匹配
我在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
agrep 包使用 Levenshtein Distances 来匹配字符串。 RecordLinkage 包有一个 C 函数来计算 Levenshtein 距离,可以直接使用它来加速计算。这是一个重新设计的
ClosestMatch
函数,速度提高了大约 10 倍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 fasterRecordLinkage 包已从 CRAN 中删除,请使用 stringdist 代替:
RecordLinkage package was removed from CRAN, use stringdist instead: