我在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)
Run Code Online (Sandbox Code Playgroud)