gpt4 book ai didi

r - agrep:只返回最佳匹配

转载 作者:行者123 更新时间:2023-12-01 23:50:31 26 4
gpt4 key购买 nike

我在 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)]

}

关于r - agrep:只返回最佳匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5721883/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com