quick way to repeat code?

panderson

New Member
Hi All!

This is my first post on this website (have been reading it for months though) so please bear with me if I don't do things right

The question I need to answer is how many rolls of a dice (in this case with 10 sides) it takes before I have seen every side. From that I need to say with 95% confidence how many rolls it will take.

I have written a code in R, it does what I want it to do (yay!) but only for one trial. I just want to know the easiest way to repeat it n times (so I can figure out the confidence part, and do a plot etc)

Here is the code:

Code:
n = 10
param = 1:n
count = 0

while(length(param) != 0){
param = setdiff(param, sample(1:n,1)) ## remove the element
count = count + 1
}

count
So when I run this I've gotten, for example, count=29, 17, 48, 23 etc but I have to keep on running it and it gets tedious!

is there an easy way to do this?

trinker

ggplot2orBust
You can take the code e4e5f4 wrote for you and make a function of it and then lapply it n times as seen below:

Code:
FUN <- function(n = 10, count = 0, param = 1:n){
while(length(param) != 0){
param = setdiff(param, sample(1:n,1)) ## remove the element
count = count + 1
}
count
}

repeats <- 30
sapply(1:repeats, function(i) FUN())

## > sapply(1:repeats, function(i) FUN())
##  [1] 36 19 20 19 29 38 21 29 43 24 26 28 22 39 38
## [16] 50 39 19 47 31 21 14 44 24 29 39 53 30 25 28
You can also use:

Code:
replicate(30, FUN())
As it's just a wrapper for what I've done above.