![](/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.