4

So as an experiment i wanted to simulate an urn with 100 balls, and R should keep extracting one of them until i get a specific ball number (in the case below the ball n100), like:

urn <- c(1:100)
num <- 0
while(num != 100){
            num <-sample(urn, 1, FALSE)
            }

But what i wanted to see is how many trials it takes on average to extract the n100 after repeating this experiment 100.000 times. I'm new to R, so i tried to make a for loop for the basic experiment to repeat it 100.000 times. Here's the code:

rep <- 100000
urn <- c(1:100)
num <- 0
trials <- 0
tottrials <-0
for (i in 1:rep){
    while(num != 100){
        num <-sample(urn, 1, FALSE)
        trials <- trials +1
        }
    tottrials <- tottrials + trials
    }
cat(prettyNum(prove, big.mark="'"),tottrials/rep,"\n")

But with this method it only do the while loop 1 time and then it repeat the found number of trials 100.000 times (instead of re-find again a new number of trials. Proof: if i make it paste the number of trials it did, he will paste the same random one 100.000 times). Why? :(

2
  • 2
    Because after num==100 the first time, it never changes. I'm not sure where you think that's changing in you loop. It's running exactly as you've coded it. Commented Oct 19, 2015 at 23:34
  • MrFlick: Right, thanks! Cleb: Sorry there should be "rep" instead of "prove". I changed variables names from Italian to English to make it easier to read but i forgot that last one. Commented Oct 20, 2015 at 10:38

1 Answer 1

4

Try putting the trials and num variables in the loop. They will reset for the next repetition:

rep <- 100000
urn <- c(1:100)
tottrials <-0
for (i in 1:rep){
    num <- 0
    trials <- 0
    while(num != 100){
        num <-sample(urn, 1, FALSE)
        trials <- trials +1
        }
    tottrials <- tottrials + trials
    }

tottrials/rep
[1] 99.51042
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.