[R] Ordering every row of a matrix while ignoring off diagonal elements
jim holtman
jholtman at gmail.com
Mon Apr 4 06:41:58 CEST 2011
I assume that this is what you did, and I would not call that
cheating; it is just a reasonable way to solve the problem:
> x <- as.matrix(read.table(textConnection(" 0.000000 2.384158 2.0065682 2.2998856
+ 2.384158 0.000000 1.4599928 2.4333213
+ 2.006568 1.459993 0.0000000 0.9733285
+ 2.299886 0.000000 0.9733285 0.0000000")))
> closeAllConnections()
> # put NAs in diagonals
> diag(x) <- NA
> # get the order
> x.ord <- t(apply(x, 1, order))
> # remove last column since this is where NAs sort
> x.ord[, -ncol(x.ord)]
[,1] [,2] [,3]
[1,] 3 4 2
[2,] 3 1 4
[3,] 4 2 1
[4,] 2 3 1
>
On Sun, Apr 3, 2011 at 11:51 PM, Vivian Shih <vivs at ucla.edu> wrote:
> 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??
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
--
Jim Holtman
Data Munger Guru
What is the problem that you are trying to solve?
More information about the R-help
mailing list