[R] Vectorize rearrangement within each column

Gabor Grothendieck ggrothendieck at gmail.com
Fri Jan 19 13:41:35 CET 2007


Turn each matrix into a data.frame and then use mapply with the "[" function,
converting back to matrix when done:

as.matrix(mapply("[", as.data.frame(ma), as.data.frame(idx)))
     V1 V2
[1,] 10 14
[2,] 12 15
[3,] 11 13


On 1/19/07, Osorio Roberto <roboso at gmail.com> 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 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