Use sample()
以(伪)随机顺序生成行索引并使用以下命令对矩阵重新排序[
.
## 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
接下来,为行生成随机顺序
## 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