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

So, as an experiment, I wanted to simulate a ballot box with 100 balls, and R should continue to mine one of them until we get a specific ball number (in the case below the ball n100), for example:

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 retrieve n100 after repeating this experiment 100,000 times. I am new to R, so I tried to make a for loop for a basic experiment to repeat it 100,000 times. Here is 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")

while 1, 100 000 ( . : if , , 100 000 ). ?: (

+4
1

trials num . reset :

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
+3

Source: https://habr.com/ru/post/1612339/


All Articles