[R] column sorting a matrix with indices returned

About this list Date view Thread view Subject view Author view Attachment view

From: Rajarshi Guha (rxg218@psu.edu)
Date: Fri 21 May 2004 - 00:11:32 EST


Message-id: <1085062292.10562.11.camel@blue.chem.psu.edu>

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@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

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://www.stat.math.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html


About this list Date view Thread view Subject view Author view Attachment view

This archive was generated by hypermail 2.1.3 : Mon 31 May 2004 - 23:05:11 EST