【问题标题】:Extract best match from string-distance matrix从字符串距离矩阵中提取最佳匹配
【发布时间】:2018-05-25 02:36:52
【问题描述】:

我无法从字符串距离矩阵中提取最佳匹配。

我正在使用包 stringdist 来计算字符串距离矩阵。

例如,我正在使用这些代码行生成我的矩阵。

library(stringdist)
lookup <- c('Dog', 'Cat', 'Bear')
data <- c('Do g', 'Do gg', 'Caat')
d.matrix <- stringdistmatrix(a = lookup, b = data, useNames="strings",method="cosine")

矩阵看起来像这样

我的方法是提取余弦相似度,最小的数字是最佳匹配。

例如,“Do g”会匹配“Dog”

我要生成的是具有余弦相似度值的匹配对数据框

data  |  matchwith  |  cosine.s

Do g       Dog         0.1338746
Do gg      Dog         0.1271284
Caat       Cat         0.05719096

我不知道如何将数据转换为我想要的表格格式(上图)。

任何帮助将不胜感激。

【问题讨论】:

    标签: r


    【解决方案1】:

    which.min 函数很好地解决了这个问题。
    这是使用基础 R 的解决方案:

    library(stringdist)
    lookup <- c('Dog', 'Cat', 'Bear')
    data <- c('Do g', 'Do gg', 'Caat')
    d.matrix <- stringdistmatrix(a = lookup, b = data, useNames="strings",method="cosine")
    
    #list of minimun cosine.s
      cosines<-apply(d.matrix, 2, min)
    
    #return list of the row number of the minimum value
      minlist<-apply(d.matrix, 2, which.min) 
    #return list of matching values
      matchwith<-lookup[minlist]
    
    #final answer
    answer<-data.frame(data, matchwith, cosines)
    

    【讨论】:

      【解决方案2】:

      这是一种蛮力技术,但你也可以说

      n.matrix <- data.frame(data=dimnames(d.matrix)[[2]], 
                             matchwith = dimnames(d.matrix)[[1]],
                             cosine.s = c(d.matrix[1,1], d.matrix[2,2], d.matrix[3,3]))
      

      如果您正在处理的实际问题中有大量列和行,则可以构建一个函数来创建 cosine.s = c(d.matrix[i,i]) 的值字符串

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-11
        • 2016-09-22
        • 1970-01-01
        • 1970-01-01
        • 2016-05-19
        • 1970-01-01
        • 1970-01-01
        • 2018-03-09
        相关资源
        最近更新 更多