随机重新排列(洗牌)矩阵的行?

9

我想随机重新排列矩阵A的行,以生成另一个新矩阵。如何在R中实现?

2个回答

18

使用sample()生成(伪)随机顺序的行索引,并使用[重新排序矩阵。

## create a matrix A for illustration
A <- matrix(1:25, ncol = 5)
给予。
> 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

接下来,为行生成一个随机顺序。

## generate a random ordering
set.seed(1) ## make reproducible here, but not if generating many random samples
rand <- sample(nrow(A))
rand
这会重复两次 "gives"。
> rand
[1] 2 5 4 3 1

现在使用它来重新排列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

9
使用tidyverse,你可以用一行代码进行洗牌:
A %>% sample_n(nrow(.))

这只适用于数据框或类似数据框的对象,因此您需要将A调整为:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接