2011-04-19 76 views
16

我在R中使用'agrep'函数,它返回一个匹配向量。我想要一个类似于agrep的函数,只返回最佳匹配,或者如果有关系,则返回最佳匹配。目前,我正在使用结果向量的每个元素上的'cba'包中的'sdist()'函数执行此操作,但这似乎非常冗余。agrep:只返回最佳匹配

/编辑:这是我目前使用的功能。我想加快速度,因为两次计算距离似乎是多余的。

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) 

回答

6

RecordLinkage包从CRAN取出10倍左右更快,使用stringdist代替:

library(stringdist) 

ClosestMatch2 = function(string, stringVector){ 

    stringVector[amatch(string, stringVector, maxDist=Inf)] 

} 
+2

Package'RecordLinkage'可用在CRAN上,再次(版本0.4-9截至2016-05-02。 – Uwe 2016-07-15 09:52:59

22

agrep包使用Levenshtein Distances匹配字符串。软件包RecordLinkage具有C函数来计算Levenshtein距离,它可以直接用于加速您的计算。这是一个经过改进的ClosestMatch功能是

library(RecordLinkage) 

ClosestMatch2 = function(string, stringVector){ 

    distance = levenshteinSim(string, stringVector); 
    stringVector[distance == max(distance)] 

} 
+0

@DWin。感谢您的更正。我编辑了我的答案以更正拼写。 – Ramnath 2011-04-20 02:51:00

+0

感谢您的回答,这是一个很棒的功能。这个包的预期目的是什么?那里可能还有其他与我的项目相关的功能。 – Zach 2011-04-20 13:25:27

+1

@Zach。是。它可能包含许多与你的工作相关的功能。在这个包的CRAN页面上有很多小插曲可以查找(http://cran.r-project.org/web/packages/RecordLinkage/index.html) – Ramnath 2011-04-20 14:26:04