随机重新排序(随机)矩阵的行? [英] Randomly re-order (shuffle) rows of a matrix?

查看:87
本文介绍了随机重新排序(随机)矩阵的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对矩阵A的行进行随机重新排序以生成另一个新矩阵.如何在R中做到这一点?

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

推荐答案

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

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)

给予

> 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

这给了

> rand
[1] 2 5 4 3 1

现在使用它来重新排序A

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

这篇关于随机重新排序(随机)矩阵的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆