【问题标题】:Efficiently accessing pairwise distances有效地访问成对距离
【发布时间】:2015-11-10 19:11:29
【问题描述】:

我有一个距离矩阵:

> mat
          hydrogen   helium  lithium beryllium    boron
hydrogen  0.000000 2.065564 3.940308  2.647510 2.671674
helium    2.065564 0.000000 2.365661  1.697749 1.319400
lithium   3.940308 2.365661 0.000000  3.188148 2.411567
beryllium 2.647510 1.697749 3.188148  0.000000 2.499369
boron     2.671674 1.319400 2.411567  2.499369 0.000000

还有一个数据框:

> results

El1      El2    Score
Helium Hydrogen   92
Boron   Helium    61
Boron  Lithium    88

我想计算results$El1 和results$El2 中单词之间的所有成对距离,得到以下结果:

> results

El1      El2    Score   Dist
Helium Hydrogen   92    2.065564
Boron   Helium    61    1.319400
Boron  Lithium    88    2.411567

我用一个 for 循环来做这个,但它看起来真的很笨重。有没有更优雅的方法可以用更少的代码来搜索和提取距离?

这是我当前的代码:

names = row.names(mat) 
num.results <- dim(results)[1]   
El1 =  match(results$El1, names)  
El2 = match(results$El2, names)    
el.dist <- matrix(0, num.results, 1)        
for (i1 in c(1:num.results)) {             
el.dist[i1, 1] <- mat[El1[i1], El2[i1]]
}
results$Dist = el.dist[,1] 

【问题讨论】:

    标签: r euclidean-distance


    【解决方案1】:
    cols <- match(tolower(results$El1), colnames(mat))
    rows <- match(tolower(results$El2), colnames(mat))
    results$Dist <- mat[cbind(rows, cols)]
    results
         El1      El2 Score     Dist
    1 Helium Hydrogen    92 2.065564
    2  Boron   Helium    61 1.319400
    3  Boron  Lithium    88 2.411567
    

    您将识别大部分代码。要关注的是mat[cbind(rows, cols)]。使用矩阵,我们可以通过另一个具有与维数相同的列数的矩阵进行子集化。来自?`[`的帮助:

    当用 [ 索引数组时,单个参数 i 可以是一个矩阵,其列数与 x 的维数一样多;结果是一个向量,其元素对应于 i 的每一行中的索引集。

    【讨论】:

    • 我发现问题后删除了之前的评论:一个流氓大写字母!
    【解决方案2】:

    另一种方法

    results$Dist <- mapply(function(x, y) mat[tolower(x), tolower(y)],
                           results$El1, results$El2)
    

    这假定results 使用character 而不是factor 用于El1 和El2。

    结果

    > results
         El1      El2 Score     Dist
    1 Helium Hydrogen    92 2.065564
    2  Boron   Helium    61 1.319400
    3  Boron  Lithium    88 2.411567
    

    【讨论】:

    • 谢谢!我刚刚尝试过,即使El1 和El2 是因素,它也能正常工作。不建议使用mapply 和因子吗?
    • @user20672 - 当可以使用整数或字符进行索引时,因子/字符差异将改变返回的结果。一个因子在内部是一个整数......所以x &lt;- c(b=1,a=2) 然后x[factor(c("a","b"))] 和x[c("a","b")] 将返回不同的答案。
    猜你喜欢
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 2019-08-03
    • 2020-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    相关资源
    最近更新 更多