我在 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)
agrep 包使用 Levenshtein Distances 来匹配字符串。 RecordLinkage 包有一个 C 函数来计算 Levenshtein 距离,可以直接使用它来加速计算。这是一个重新设计的ClosestMatch
速度快 10 倍左右的函数
library(RecordLinkage)
ClosestMatch2 = function(string, stringVector){
distance = levenshteinSim(string, stringVector);
stringVector[distance == max(distance)]
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)