rsamplemultisampling

Multiple random samples without replacement in R


I have a vector of size M = 2630, How can I draw 4 samples of size M/4. The following code is not working

M <- c(1:2630)
mysample <- split(sample(M), 1:(length(M)/4))

Since (length(M)/4) is not an integer, So I would like to make three samples of equal size and the fourth will have the rest of the units. Three samples can be of size 657 and the fourth one can be 659.

Any help is appreciated


Solution

  • Here is an easy way using a separate index vector idx:

    n <- length(M)
    set.seed(1)
    idx <- sample(rep(1:4, each = ceiling(n /4))[1:n])
    
    M1 <- M[idx == 1]
    M2 <- M[idx == 2]
    M3 <- M[idx == 3]
    M1 <- M[idx == 4]
    

    Or you use the split function:

    split(M, idx)
    

    Note that I set a random seed using set.seed to make the results reproducible.

    You can use table to check the values of idx:

    table(idx)
    idx
      1   2   3   4 
    658 658 658 656