Randomly re-order (shuffle) rows of a matrix?
Asked Answered
G

2

11

I would like to randomly re-order the rows of matrix A to generate another new matrix. How to do that in R?

Gammadion answered 31/1, 2012 at 14:47 Comment(0)
W
20

Use sample() to generate row-indices in a (pseudo-)random order and reorder the matrix using [.

## create a matrix A for illustration
A <- matrix(1:25, ncol = 5)

Giving

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

Next, generate a random order for the rows

## generate a random ordering
set.seed(1) ## make reproducible here, but not if generating many random samples
rand <- sample(nrow(A))
rand

This gives gives

> rand
[1] 2 5 4 3 1

Now use that to reorder A

> A
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    6   11   16   21
[2,]    2    7   12   17   22
[3,]    3    8   13   18   23
[4,]    4    9   14   19   24
[5,]    5   10   15   20   25
> A[rand, ]
     [,1] [,2] [,3] [,4] [,5]
[1,]    2    7   12   17   22
[2,]    5   10   15   20   25
[3,]    4    9   14   19   24
[4,]    3    8   13   18   23
[5,]    1    6   11   16   21
Warder answered 31/1, 2012 at 14:55 Comment(0)
B
9

With tidyverse, you can shuffle with a one-liner:

A %>% sample_n(nrow(.))

This only works on a dataframe or tibble, so you need to get A as:

A <- tibble(1:25, ncol = 5)
A %>% sample_n(nrow(.))

# A tibble: 25 x 2
   `1:25`  ncol
    <int> <dbl>
 1      9     5
 2      6     5
 3      4     5
 4     15     5
 5     14     5
 6      3     5
 7     23     5
 8     25     5
 9     17     5
10     19     5
# … with 15 more rows
Barometer answered 3/7, 2020 at 3:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.