user18487205
user18487205

Reputation: 51

Create a vector containt 200 times a random sample of 20 in R

I have to create a vector which contains 200 times a random sample of 20 numbers (always number 1 to 20 but in a random order). I tried to do this with a for loop and with sample(20) but it did not work. can someone help me?

Upvotes: 0

Views: 259

Answers (2)

langtang
langtang

Reputation: 24845

You can try this:

unlist(lapply(1:200, function(x) sample(1:20)))

or

c(sapply(1:200,\(x) sample(1:20)))

The result is 4000 elements long, which I think is what you want (200 consecutive samples of 1:20)

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 102710

We can use replicate + sample

replicate(200, sample(20))

which works in an easy way than for loops

Upvotes: 3

Related Questions