Re: [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:22:45 EST


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

On Thu, 2004-05-20 at 10:11, Rajarshi Guha wrote:
> 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

I worked out a way:

sorted <- apply(x, c(2), sort, index.return=T)

sortedmatrix <- matrix(unlist(lapply(sorted, function(x) { x$x })),
nr=length(sortstruct))

sortedindices <- matrix(unlist(lapply(sorted, function(x) { x$ix })),
nr=length(sorted))

Is this efficient, as the matrices will be large (or can it be made
into a 1 liner)?

-------------------------------------------------------------------
Rajarshi Guha <rxg218@psu.edu> <http://jijo.cjb.net>
GPG Fingerprint: 0CCA 8EE2 2EEB 25E2 AB04 06F7 1BB9 E634 9B87 56EE
-------------------------------------------------------------------
A man is known by the company he organizes.
-- Ambrose Bierce

______________________________________________
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