Search code examples
rsamplerep

Sample in for loop R


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?


Solution

  • 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"