Re: [R] Vectorize rearrangement within each column

From: Patrick Burns <pburns_at_pburns.seanet.com>
Date: Fri 19 Jan 2007 - 10:53:04 GMT

Matrix subscripting can be used for this:

 > mb <- ma[cbind(as.vector(idx), as.vector(col(idx)))]
 > dim(mb) <- dim(ma)
 > mb
     [,1] [,2]
[1,]   10   14

[2,] 12 15
[3,] 11 13

Patrick Burns
patrick@burns-stat.com
+44 (0)20 8525 0696
http://www.burns-stat.com
(home of S Poetry and "A Guide for the Unwilling S User")

Osorio Roberto wrote:

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



R-help@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. Received on Fri Jan 19 22:26:48 2007

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Fri 19 Jan 2007 - 12:30:27 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.