2
votes

I'd like to sample without replacement from MU, MG, PU, PG 70 times to create a matrix (ncol=4, nrow=70) e.g.

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

So far I have: matrix(sample(c("MU","MG","PU","PG"), 70*4,F), nrow = 70, byrow = TRUE) which isn't right because the rows may have more than just on instance each of MU, MG, PU, PG. Can I do this with a for loop or something more simple?

3

3 Answers

4
votes

The replicate function might be what you're looking for. I'll only do 10 replicates to not overflow the screen.

> 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"
3
votes

A quick solution would be a loop:

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

And for those allergic to loops:

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

You can try this also:

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

Sample of some rows as an output:

 #[,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"