[R] Permuting rows of a matrix

Diogo Almeida dalazal at gmail.com
Thu Feb 10 07:45:46 CET 2011


Hi,

I need to permute the rows of a matrix, where each row is independently rearranged. A simple solution is this:

shuffled <- datamatrix <- matrix(1:24, ncol = 4)
for (i in 1:nrow(datamatrix)) { shuffled[i, ] <- sample(datamatrix[i, ]) }

> datamatrix
     [,1] [,2] [,3] [,4]
[1,]    1    7   13   19
[2,]    2    8   14   20
[3,]    3    9   15   21
[4,]    4   10   16   22
[5,]    5   11   17   23
[6,]    6   12   18   24
> shuffled
     [,1] [,2] [,3] [,4]
[1,]    7   19   13    1
[2,]    2    8   14   20
[3,]   15    3    9   21
[4,]   22   10   16    4
[5,]    5   11   17   23
[6,]   24    6   12   18

However, I need to perform quite a lot of these permutations, and I was wondering whether anyone knows of a faster way of doing this. Something that might not involve a "for" loop, for instance?
-Diogo


More information about the R-help mailing list