![](/img/trans.png)
[英]Matching rownames that are equal to colnames (of a symmetric or asymmetric matrix)
[英]R get highest x cells and their rownames/colnames in a symmetric matrix?
我有一個對稱矩陣mat
:
A B C
A 1 . .
B . 1 .
C . . 1
我想計算其中的兩個最高元素。 現在,由於它是一個對稱矩陣,因此我想到像這樣使用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
因此,以上是這種回旋處理方式,即使這樣,輸出仍具有“重復”行,因為它們只是轉置了。
有人有更直觀的方法嗎?
謝謝。
自由地借鑒@SimonO'Hanlon
和@lukeA
的出色思想,您可以構造一個兩層函數來完成您想要的事情。 我用:
arrayInd()
返回數組索引 order()
對上三角元素進行排序 m[lower.tr(m)] <- NA
將下三角矩陣設置為NA
的其他技巧 嘗試這個:
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.