user9369411
user9369411

Reputation: 29

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

Upvotes: 0

Views: 316

Answers (3)

Brian Davis
Brian Davis

Reputation: 992

Another method...

x <- 1:20
matrix(x[sample(seq_along(x),length(x))],ncol = 4)

Here we are randomly reordering your vector by sampling index values, then dumping results into a matrix so that its columns represent your five groups. You could also leave it as a vector, or make a list if you don't want your output as a matrix.

Upvotes: 1

IceCreamToucan
IceCreamToucan

Reputation: 28675

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

Upvotes: 2

Andrew Gustar
Andrew Gustar

Reputation: 18425

You could do something like this...

l <- as.list(LETTERS[1:25])

l2 <- split(l,rep(1:5,5)[sample(25)])

l2 #is then a list of five lists containing all elements of l...
$`1`
$`1`[[1]]
[1] "D"

$`1`[[2]]
[1] "I"

$`1`[[3]]
[1] "M"

$`1`[[4]]
[1] "W"

$`1`[[5]]
[1] "Y"


$`2`
$`2`[[1]]
[1] "C"

$`2`[[2]]
[1] "E"

$`2`[[3]]
[1] "H"

$`2`[[4]]
[1] "T"

$`2`[[5]]
[1] "X"
 etc...

Upvotes: 0

Related Questions