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 <[EMAIL PROTECTED]> <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
______________________________________________
[EMAIL PROTECTED] 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