Zac*_*ach 23 text r character string-matching 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)
Run Code Online (Sandbox Code Playgroud)
Ram*_*ath 27
agrep包使用Levenshtein距离来匹配字符串.RecordLinkage包具有C函数来计算Levenshtein距离,可以直接用于加速计算.这是一个重做的ClosestMatch功能,速度提高了大约10倍
library(RecordLinkage)
ClosestMatch2 = function(string, stringVector){
distance = levenshteinSim(string, stringVector);
stringVector[distance == max(distance)]
}
Run Code Online (Sandbox Code Playgroud)
Ale*_*hov 11
RecordLinkage包已从CRAN中删除,请改为使用stringdist:
library(stringdist)
ClosestMatch2 = function(string, stringVector){
stringVector[amatch(string, stringVector, maxDist=Inf)]
}
Run Code Online (Sandbox Code Playgroud)