0

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

Cettt
  • 11,460
  • 7
  • 35
  • 58
Uddin
  • 754
  • 5
  • 18
  • FYI `length(M)` is 1. Do you mean `length(seq(M))`? (or just M)...? – Sotos Nov 19 '19 at 15:45
  • I have edited the question and included M – Uddin Nov 19 '19 at 15:49
  • Possible duplicate since the problem just seems to be creating equal groups: https://stackoverflow.com/questions/33262795/how-to-split-a-dataset-to-n-equally-sized-groups-and-assign-them-a-number – MrFlick Nov 19 '19 at 15:52

1 Answers1

2

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
Cettt
  • 11,460
  • 7
  • 35
  • 58