【问题标题】:Why does agrep in R not find the best match?为什么 R 中的 agrep 找不到最佳匹配?
【发布时间】:2017-04-07 17:46:20
【问题描述】:

我正在使用 agrep 命令在 R 中尝试字符串匹配。 但是我担心它会在找到一个好的匹配时停止,而不是优化以找到最好的匹配。尽管我对它的工作原理的理解可能不正确。我下面的例子重现了这个问题,虽然很粗糙。

example1 <- c("height","weight")
example2 <- c("height","weight")

y <- c("","")
for( i in 1: 2 ){
x <- agrep(example1[i], example2, max.distance = 1, ignore.case=TRUE, value=TRUE, useBytes=TRUE ) 
x <- paste0(x,"")
y[i] <- x
  }

正如您所希望看到的,agrep 已将体重与身高相匹配,而体重是更好的匹配并且也存在。

这是为什么?

【问题讨论】:

  • x是两个值的向量,但只有第一个被赋值给y(你应该有警告),所以只给出height
  • 所以 x 包含所有符合条件的匹配项,我只是选择其中的第一个,这不一定是最佳匹配项?有没有办法只提取最好的?目前,我必须先进行精确匹配,然后进行模糊匹配才能解决问题。然而,这个例子并没有让我对其余的模糊匹配充满信心。
  • 是的,就是这样。你可以看看this question for the best match
  • 感谢您的帮助。

标签: r agrep


【解决方案1】:

您可以尝试 adist(用于广义 Levenshtein(编辑)距离),结果如下(示例 1 中的“高度”与示例 2 中的高度最佳匹配等):

adist(example1, example2)
     [,1] [,2]
[1,]    0    1
[2,]    1    0

example2[apply(adist(example1, example2), 1, which.min)]
# [1] "height" "weight"

【讨论】:

    猜你喜欢
    • 2011-08-08
    • 1970-01-01
    • 2014-08-26
    • 1970-01-01
    • 2012-12-21
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    相关资源
    最近更新 更多