[R] Ordering every row of a matrix while ignoring off diagonal elements

Vivian Shih vivs at ucla.edu
Mon Apr 4 05:51:33 CEST 2011


Sorry if this is a stupid question but I've been stuck on how to code  
so that I can order rows of a matrix without paying attention to the  
diagonal elements.

Say, for example, I have a matrix d:
> d
          [,1]     [,2]      [,3]      [,4]
[1,] 0.000000 2.384158 2.0065682 2.2998856
[2,] 2.384158 0.000000 1.4599928 2.4333213
[3,] 2.006568 1.459993 0.0000000 0.9733285
[4,] 2.299886 0.000000 0.9733285 0.0000000

Then I'd like ordered d to be like:
      [,1] [,2] [,3]
[1,]    3    4    2
[2,]    3    1    4
[3,]    4    2    1
[4,]    2    3    1

So subject 1's smallest value is in column 3. Subject 2's second  
smallest value would be 3, etc. Note that subject 4 has two zeros (a  
"tie") but if the diagonals are not in the equation, then the minimum  
value for this subject is from column 2.

Right now I coded off diagonals as missing and then order it that way  
but I feel like it's cheating. Suggestions??



More information about the R-help mailing list