Tou Mou
Tou Mou

Reputation: 1274

How to permute rows of a given matrix

Good morning !

Assume we have the following matrix :

m=matrix(1:18,ncol=2)
print("m : before")
print(m)

[1] "m : before"
      [,1] [,2]
 [1,]    1   10
 [2,]    2   11
 [3,]    3   12
 [4,]    4   13
 [5,]    5   14
 [6,]    6   15
 [7,]    7   16
 [8,]    8   17
 [9,]    9   18

As an example, I'm wanting to permute a number of rows :

tmp=m[8:9,]
m[8:9,]=m[3:4,]
m[3:4,]=tmp

This is the same as :

# indices to permute 
before=8:9
after=3:4

tmp=m[before,]
m[before,]=m[after,]
m[after,]=tmp


[1] "after"
     [,1] [,2]
 [1,]    1   10
 [2,]    2   11
 [3,]    8   17
 [4,]    9   18
 [5,]    5   14
 [6,]    6   15
 [7,]    7   16
 [8,]    3   12
 [9,]    4   13

I'm wanting to know if there is any package that automatize such task. For the moment , I'm not willing to use a user-defined function.

Thank you for help !

Upvotes: 0

Views: 229

Answers (2)

Peace Wang
Peace Wang

Reputation: 2419

Just try to exchange the index order.

m[c(before,after),] = m[c(after,before),]

Upvotes: 1

Elia
Elia

Reputation: 2584

I think the simplest solution is just to use base r function, like sample:

set.seed(4)
m[sample(1:nrow(m),nrow(m)),]

which give you:

  [,1] [,2]
 [1,]    8   17
 [2,]    3   12
 [3,]    9   18
 [4,]    7   16
 [5,]    4   13
 [6,]    6   15
 [7,]    2   11
 [8,]    1   10
 [9,]    5   14

If you want to permute just some rows you can do :

m[7:9,] <- m[sample(7:9,3),]#where the last number (3) is the number of row 
to permute

which give you

   [,1] [,2]
 [1,]    1   10
 [2,]    2   11
 [3,]    3   12
 [4,]    4   13
 [5,]    5   14
 [6,]    6   15
 [7,]    7   16
 [8,]    9   18
 [9,]    8   17

Upvotes: 2

Related Questions