for循环R中的样本

Sample in for loop R

我想从 MU、MG、PU、PG 中采样 70 次以创建矩阵(ncol=4,nrow=70) 例如

sample(c("MU","MG","PU","PG"), 4,F)
sample(c("MU","MG","PU","PG"), 4,F)
sample(c("MU","MG","PU","PG"), 4,F)
sample(c("MU","MG","PU","PG"), 4,F)
sample(c("MU","MG","PU","PG"), 4,F)
#etc

到目前为止我有: 矩阵(样本(c("MU","MG","PU","PG"), 70*4,F), nrow = 70, byrow = TRUE) 这不是正确,因为这些行可能不仅仅包含 MU、MG、PU、PG 中的每个实例。我可以使用 for 循环或更简单的方法来做到这一点吗?

replicate 函数可能正是您要找的。我只会重复 10 次,以免溢出屏幕。

> sample(c("MU","MG","PU","PG"), 4,F)
[1] "MG" "MU" "PU" "PG"
> replicate(10, sample(c("MU","MG","PU","PG"), 4,F))
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] "MG" "PG" "MU" "MU" "PU" "MG" "PU" "MG" "MG" "MU" 
[2,] "PU" "MG" "PU" "PU" "MU" "MU" "MU" "PG" "MU" "PG" 
[3,] "MU" "PU" "MG" "PG" "MG" "PG" "MG" "MU" "PG" "MG" 
[4,] "PG" "MU" "PG" "MG" "PG" "PU" "PG" "PU" "PU" "PU" 
> # Output is transposed from how we would want it so we'll just transpose it back
> t(replicate(10, sample(c("MU","MG","PU","PG"), 4,F)))
      [,1] [,2] [,3] [,4]
 [1,] "MG" "PU" "PG" "MU"
 [2,] "PU" "MG" "MU" "PG"
 [3,] "MG" "MU" "PU" "PG"
 [4,] "PU" "PG" "MU" "MG"
 [5,] "MG" "PU" "PG" "MU"
 [6,] "PU" "PG" "MU" "MG"
 [7,] "PG" "MG" "PU" "MU"
 [8,] "MU" "PU" "MG" "PG"
 [9,] "PG" "MU" "PU" "MG"
[10,] "MU" "MG" "PG" "PU"

一个快速的解决方案是一个循环:

mat <- matrix(NA_character_, nrow = 70, ncol = 4)
for (i in 1:70) {
  mat[i, ] <- sample(c("MU","MG","PU","PG"), 4, replace = FALSE)
}

对于那些对循环过敏的人:

t(sapply(1:70, function(x) sample(c("MU","MG","PU","PG"), 4, replace = FALSE)))

你也可以试试这个:

lyst <- lapply( 1:70, function(x) {set.seed(x); sample(c("PU", "MU", "MG", "PG"), 4, replace=F)})
do.call("rbind", lyst)

一些行的样本作为输出:

 #[,1] [,2] [,3] [,4]
 #[1,] "MU" "PG" "MG" "PU"
 #[2,] "PU" "MG" "MU" "PG"
 #[3,] "PU" "MG" "PG" "MU"
 #[4,] "MG" "PU" "PG" "MU"
 #[5,] "PU" "MG" "MU" "PG"