简体   繁体   中英

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

I have a symmetric matrix 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:

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. I use:

  • arrayInd() to return the array index
  • order() to order the upper triangular elements
  • and the additional trick of setting the lower triangular matrix to NA , using m[lower.tr(m)] <- 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,]相同,但效率更高。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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