简体   繁体   中英

Reorder symmetric matrix in R

EDITED: Suppose I have a symmetric matrix such as the one below.

dat<-c(NA,2,3,4,5,2,NA,8,9,10,3,8,NA,14,15,4,9,14,NA,20,5,10,15,20,NA)
x<-matrix(dat,nrow = 5,dimnames = list(c("A","B","C","D","E"),c("A","B","C","D","E")))
x

I'm trying to see if there is any way we can use R to reorder the matrix in such a way that the highest values are closer to the diagonal, with the maximum value of each column of the lower triangle as the first item in the diagonal, and also it maintains its symmetry. This is a problem in card sorting.

Here is the desired output:

result<-c(NA,20,15,10,5,20,NA,14,9,4,15,14,NA,8,3,10,9,8,NA,2,5,4,3,2,NA)
y<-matrix(result,nrow = 5,dimnames = list(c("E","D","C","B","A"),c("E","D","C","B","A")))
y

I had a similar requirement when examining a matrix containing similarities between documents.

k <- apply(x, 1, max, na.rm=TRUE)
order <- sort(k, decreasing=TRUE, index.return=TRUE)$ix
x[order, order]

I use max on each row to find the maximum value per row. na.rm ensures that the diagonal is not considered. sort then provides the desired order as a vector. Reorganising the matrix according to that order is as simple as x[order, order] .

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