Search code examples
rrandomuniquesample

sample list randomly and remove used values


I have a problem (maybe it is not that difficult but I cannot figure it out:

I have a list (l) of 25 and I want to divide the list into 5 groups but randomly. The problem I have is if I use sample(l, 5) and this 5times it does not give me unique samples. So basically, I am looking for is to choose 5 then remove them from the list and then sample again.

I hope someone has a solution... thanks


Solution

  • If you want Andrew's method as a function

    sample2 <- function(x, sample.size){
     split(x, sample(ceiling(seq_along(x)/sample.size)))
    }
    
    sample2(1:20, 5)
    

    gives

    $`1`
    [1]  1 15  6  3 18
    
    $`2`
    [1] 11  7  5 10 14
    
    $`3`
    [1]  2 12  4 13 17
    
    $`4`
    [1] 19 16 20  8  9