As with most things like this, you can trade memory for speed.  Here is
an obfuscated solution that appears to eschew loops entirely.

> ma <- matrix(10:15, nr = 3)
> idx <- matrix(c(1,3,2, 2,3,1), nr = 3)
> mb <- ma
> mb[] <- as.vector(ma)[as.vector(idx + 
        outer(rep(nrow(ma), nrow(ma)), 1:ncol(ma)-1, '*'))]
> mb
     [,1] [,2]
[1,]   10   14
[2,]   12   15
[3,]   11   13

Ordinarily, though, my preferred solution would be the for() loop.

Bill Venables
CMIS, CSIRO Laboratories,
PO Box 120, Cleveland, Qld. 4163
AUSTRALIA
Office Phone (email preferred): +61 7 3826 7251
Fax (if absolutely necessary):    +61 7 3826 7304
Mobile (rarely used):                +61 4 1963 4642
Home Phone:                          +61 7 3286 7700
mailto:[EMAIL PROTECTED]
http://www.cmis.csiro.au/bill.venables/ 
 
 

-----Original Message-----
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of Osorio Roberto
Sent: Friday, 19 January 2007 4:15 PM
To: [email protected]
Subject: [R] Vectorize rearrangement within each column

Consider a matrix like

 > ma = matrix(10:15, nr = 3)
 > ma
      [,1] [,2]
[1,]   10   13
[2,]   11   14
[3,]   12   15

I want to rearrange each column according to row indexes (1 to 3)  
given in another matrix, as in

 > idx = matrix(c(1,3,2, 2,3,1), nr = 3)
 > idx
      [,1] [,2]
[1,]    1    2
[2,]    3    3
[3,]    2    1

The new matrix mb will have for each column the corresponding column  
of ma indexed by the corresponding column of idx, as in

 > mb = ma
 > for (j in 1:2) mb[,j] = ma[idx[,j], j]       
 > mb
      [,1] [,2]
[1,]   10   14
[2,]   12   15
[3,]   11   13

Can I avoid the for() loop? I'm specially interested to find out if a  
fast implementation using lapply() would be feasible for large input  
matrices (analogues of ma and idx) transformed into data frames.

Roberto Osorio

______________________________________________
[email protected] 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.

______________________________________________
[email protected] 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.

Reply via email to