Search code examples
rblocksample

R: How to create a equal blocks of variables randomly?


I have a data frame of n = 20 variables (number of columns) spread over b = 5 blocks (4 variables per block). I would like to create p = 4 random and equal sized blocks of variables from the 5 blocks of variables.

I tried :

sample (x = 1: p, size = n, replace = TRUE) 
[1] 1 1 1 1 1 1 1 1 1 2 2 2 3 3 3 4 4 4 4 4

Example of expected result (5 variables per block):

[1] 4 1 2 1 4 2 3 1 2 3 2 1 4 3 1 2 3 3 4 4 

Thanks for your help !


Solution

  • You can try:

    sample(x = rep(1:p,n/p), size = n, replace = FALSE)