随机播放列值但保持相同的矩阵列排序

时间:2014-09-06 08:02:40

标签: r matrix shuffle

如何在每列中混合矩阵m1的值:

初​​始:

m1=cbind(c(1,2,3),c(4,5,6),c(7,8,9))

做点什么,然后:

m1=cbind(c(7,5,3),c(4,2,9),c(1,8,6))

由于

3 个答案:

答案 0 :(得分:2)

嗯,你的意思是你的例子中的行?!

随机播放列表:

# create a list from 1 to 9
x <- seq(1,9)
# shuffle
x[order(runif(length(x)))]

随机播放矩阵的行/列:

# example matrix
m1 <- matrix(x,ncol=3)
# shuffle by row
for (i in 1:nrow(m1)) m1[i,] <- m1[i,order(runif(length(m1[i,])))]
# shuffle by col
for (i in 1:ncol(m1)) m1[,i] <- m1[order(runif(length(m1[i,]))),i]

编辑:也许sample更好...... http://stat.ethz.ch/R-manual/R-devel/library/base/html/sample.html

答案 1 :(得分:2)

您可以在矩阵的每一列上调用sample函数来对其进行随机播放:

set.seed(100)
apply(m1, 2, sample)
#      [,1] [,2] [,3]
# [1,]    1    5    8
# [2,]    3    4    9
# [3,]    2    6    7

答案 2 :(得分:1)

您还可以将sample放入矩阵索引中并对行和列进行采样。

改组整个矩阵,

> m1[sample(nrow(m1)), sample(ncol(m1))]
#     [,1] [,2] [,3]
#[1,]    6    9    3
#[2,]    5    8    2
#[3,]    4    7    1

或按行

> m1[sample(nrow(m1)), ]
#     [,1] [,2] [,3]
#[1,]    3    6    9
#[2,]    1    4    7
#[3,]    2    5    8

或按列

> m1[,sample(ncol(m1))]
#     [,1] [,2] [,3]
#[1,]    7    4    1
#[2,]    8    5    2
#[3,]    9    6    3