[R] Vectorize rearrangement within each column

Bill.Venables at csiro.au Bill.Venables at csiro.au
Fri Jan 19 09:00:05 CET 2007


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:Bill.Venables at csiro.au
http://www.cmis.csiro.au/bill.venables/ 
 
 

-----Original Message-----
From: r-help-bounces at stat.math.ethz.ch
[mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Osorio Roberto
Sent: Friday, 19 January 2007 4:15 PM
To: r-help at stat.math.ethz.ch
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

______________________________________________
R-help at stat.math.ethz.ch 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.



More information about the R-help mailing list