Skip to content
Prev 277631 / 398513 Next

permutation within rows of a matrix

On Wed, 2011-11-16 at 14:29 -0500, R. Michael Weylandt wrote:
That will shuffle the rows at random, not permute within the rows.

Here is an alternative, first using one of my packages (permute -
shameful promotion ;-) !:

mat <- matrix(sample(0:1, 100, replace = TRUE), ncol = 10)

require(permute)
perms <- shuffleSet(10, nset = 10)
## permute mat
t(sapply(seq_len(nrow(perms)), 
         function(i, perms, mat) mat[i, perms[i,]],
         mat = mat, perms = perms))

If you don't want to use permute, then you can do this via standard R
functions

perms <- t(replicate(nrow(mat), sample(ncol(mat))))
## permute mat
t(sapply(seq_len(nrow(perms)), 
         function(i, perms, mat) mat[i, perms[i,]],
         mat = mat, perms = perms))

HTH

G