简体   繁体   English

R在对称矩阵中获得最高的x个单元格及其行名/同名?

[英]R get highest x cells and their rownames/colnames in a symmetric matrix?

I have a symmetric matrix mat : 我有一个对称矩阵mat

   A  B  C
A  1  .  .
B  .  1  .
C  .  .  1

And I want to calculate the two highest elements of it. 我想计算其中的两个最高元素。 Now since it's a symmetric matrix I thought of using upper.tri like so: 现在,由于它是一个对称矩阵,因此我想到像这样使用upper.tri

mat.tri<-upper.tri(mat) # convert to upper tri
mat.ord<-order(mat.tri,na.last=TRUE,decreasing=TRUE)[1:2] # order by largest
a.ind<-which(mat%in%mat.tri[mat.ord]) # get absolute indices
r.ind<-arrayInd(a.ind,dim(mat)) # get relative indices
# get row/colnames using these indices

So the above is such a roundabout way of doing things, and even then the output has 'duplicate' rows in that they are just transposed.. 因此,以上是这种回旋处理方式,即使这样,输出仍具有“重复”行,因为它们只是转置了。

Anyone got a more intuitive way of doing this? 有人有更直观的方法吗?

Thanks. 谢谢。

Liberally borrowing from the excellent ideas of @SimonO'Hanlon and @lukeA , you can construct a two-liner function to do what you want. 自由地借鉴@SimonO'Hanlon@lukeA的出色思想,您可以构造一个两层函数来完成您想要的事情。 I use: 我用:

  • arrayInd() to return the array index arrayInd()返回数组索引
  • order() to order the upper triangular elements order()对上三角元素进行排序
  • and the additional trick of setting the lower triangular matrix to NA , using m[lower.tr(m)] <- NA 以及使用m[lower.tr(m)] <- NA将下三角矩阵设置为NA的其他技巧

Try this: 尝试这个:

whichArrayMax <- function(m, n=2){
  m[lower.tri(m)] <- NA
  arrayInd(order(m, decreasing=TRUE)[seq(n)], .dim=dim(m))
}

mat <- matrix( c(1,2,3,2,1,5,3,5,1) , 3 , byrow = TRUE )
mat

     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    2    1    5
[3,]    3    5    1

whichArrayMax(mat, 2)
     [,1] [,2]
[1,]    2    3
[2,]    1    3
arrayInd(which.max(mat), .dim=dim(mat))

它与@ SimonO'Hanlon中的which( mat == max(mat) , arr.ind = TRUE )[1,]相同,但效率更高。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM