简体   繁体   中英

sorting correlation matrix R

I have created a correlation matrix in R, using the cor function.

I would like to extract the 10 largest (closest to 1) and 10 smallest (closest to -1) from this matrix with the corresponding row and column indices.

Here is a sample code of how I am obtaining the correlation matrix:

  xs = rnorm(10000)
ys = rnorm(10000)
zs = rnorm(10000)

cor1 <- cor(data.frame(xs,ys,zs))

I obtain:

      xs          ys          zs
xs  1.00000000 -0.01077785 -0.01308803
ys -0.01077785  1.00000000  0.01176254
zs -0.01308803  0.01176254  1.00000000

Any suggestions?

Thanks!

If mat is your correlation matrix, you can get the locations of the top and bottom 10 like this...

min10 <- which(mat<=sort(mat)[10], arr.ind = TRUE)
max10 <- which(-mat<=sort(-mat)[10], arr.ind = TRUE)

Each of these is a nx 2 matrix, where the columns are the row and column numbers of mat for those elements meeting the criteria.

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