[R] Permutation of Matrix

Marc Schwartz marc_schwartz at me.com
Tue Apr 6 00:49:39 CEST 2010


On Apr 5, 2010, at 5:25 PM, David Winsemius wrote:

> 
> On Apr 5, 2010, at 4:58 PM, Ayush Raman wrote:
> 
>> Hi all,
>> 
>> How can I have a permuted matrix where the second row is the permutation
>> over the first row ; third is the permutation of the second row; forth is
>> the permutation of the third row and so on ?
> 
> Wouldn't any of those permutations just be a permutation of the first row? Perhaps something like:
> 
> 
> M <- matrix(first_row, length(first_row), length(first_row))
> M[1, ] <- first_row
> M[2:length(first_row), ] <- rbind(
>          t(sapply(2:length(first_row), function(x) {
>                       sample(first_row, length(first_row), replace=FALSE) }
>            )     )
>                                 )


How about something like this:

# set first row entries
row1 <- 1:6

# Total desired rows, including above
totalrows <- 5


set.seed(1)

> rbind(row1, t(replicate(totalrows - 1, sample(row1))), deparse.level = 0)
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    2    3    4    5    6
[2,]    2    6    3    4    1    5
[3,]    6    4    3    1    5    2
[4,]    5    2    4    6    3    1
[5,]    3    4    5    1    2    6

?

HTH,

Marc Schwartz



More information about the R-help mailing list