簡體   English   中英

隨機重新排序(洗牌)矩陣的行?

[英]Randomly re-order (shuffle) rows of a matrix?

我想隨機重新排序矩陣 A 的行以生成另一個新矩陣。 如何在 R 中做到這一點?

使用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

這給了

> 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

使用 tidyverse,您可以使用 one-liner 進行 shuffle:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM