[R] column sorting a matrix with indices returned

Rajarshi Guha rxg218 at psu.edu
Thu May 20 16:11:32 CEST 2004


Hi,
  I'm trying to translate some Matlab code to R and I'm trying to
implement the behavior of Matlab's sort() which when applied to a matrix
will sort the columns returning the column  sorted matrix as well as a
matrix of permuted indices.

Doing:

> x <- matrix(c(3,4,2,6,3,4,8,7,5), nr=3)
> x
     [,1] [,2] [,3]
[1,]    3    6    8
[2,]    4    3    7
[3,]    2    4    5

What I want after sorting x are two matrices:

(the column sorted x)
2 3 5
3 4 7
4 6 8

and (the index matrix)
3 2 3
1 3 2
2 1 1

Doing,
> sx <- apply(x, c(2), sort, index.return=T)

results in sx being a series of lists. I know I could then go through
the list and create a sorted matrix and an index matrix. 

But is there a neater way to do this?

Thanks,

-------------------------------------------------------------------
Rajarshi Guha <rxg218 at psu.edu> <http://jijo.cjb.net>
GPG Fingerprint: 0CCA 8EE2 2EEB 25E2 AB04 06F7 1BB9 E634 9B87 56EE
-------------------------------------------------------------------
Accuracy, n.:
The vice of being right




More information about the R-help mailing list