Federico Secco
Federico Secco

Reputation: 53

"while loop" inside a "for loop" in R not working?

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? :(

Upvotes: 4

Views: 4731

Answers (1)

Pierre L
Pierre L

Reputation: 28461

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

Upvotes: 4

Related Questions