[R] Getting the row/column of matrix for some values?

Marc Schwartz MSchwartz at MedAnalytics.com
Thu Apr 14 04:27:26 CEST 2005


On Wed, 2005-04-13 at 21:09 -0500, Chris Bergstresser wrote:
> Hi all --
> 
>     Quick (I hope) question: I've got a correlation matrix.  Is there a 
> quick way to find all the row/column names for those correlations higher 
> than some value, like 0.4?

> mat <- cor(matrix(rnorm(100), ncol = 5))

> mat
            [,1]        [,2]        [,3]        [,4]        [,5]
[1,]  1.00000000  0.08406738 -0.18412634 -0.15484250  0.18975606
[2,]  0.08406738  1.00000000  0.06242012  0.44583819 -0.03338074
[3,] -0.18412634  0.06242012  1.00000000  0.01045560  0.16876206
[4,] -0.15484250  0.44583819  0.01045560  1.00000000  0.26283234
[5,]  0.18975606 -0.03338074  0.16876206  0.26283234  1.00000000

# Get row/col positions
> which(mat > 0.4, arr.ind = TRUE)
     row col
[1,]   1   1
[2,]   2   2
[3,]   4   2
[4,]   3   3
[5,]   2   4
[6,]   4   4
[7,]   5   5

# Get the actual values
> mat[which(mat > 0.4, arr.ind = TRUE)]
[1] 1.0000000 1.0000000 0.4458382 1.0000000 0.4458382 1.0000000
[7] 1.0000000

See ?which for more information.

HTH,

Marc Schwartz




More information about the R-help mailing list