First, here's an explanation of each step:
nreps <- 10000
nstops <- 10
count <- 0
for (i in 1:nreps){ #for 10,000 iterations
passengers <- 0 #start with zero passengers
for (j in 1:nstops){ #for the number of stops (10) do...
if(passengers > 0) #for number of passengers, when number > 0...
for (k in 1:passengers) #for each passenger...
if(runif(1) < 0.2) #take 1 random val from a uniform dist, and if less than 0.2...
passengers <- passengers - 1 #subtract 1 from passengers (i.e. n-1)
newpass <- sample(0:2, 1, prob=c(0.5, 0.4, 0.1)) #take one random sample from 0,1,2, with probability weights 0.5, 0.4, 0.1, respectively
passengers <- passengers + newpass #add existing passengers to number of new passengers
}
if (passengers == 0) count <- count + 1 #if the number of passengers still equal zero by now, add 1 to the count
}
print(count/nreps) #number of times when passenger = 0 divided by number of iterations
Now, if you want to track the progress of each iteration, you can first set up empty variables, then fill those variables according to the index of each iteration, like this:
passengers_before <- c() #empty vector
passengers_after <- c() #empty vector
for (i in 1:nreps){ #for 10,000 iterations
passengers <- 0 #start with zero passengers
passengers_before[i] <- passengers
for (j in 1:nstops){ #for the number of stops (10) do...
if(passengers > 0) #for number of passengers, when number > 0...
for (k in 1:passengers) #for each passenger...
if(runif(1) < 0.2) #take 1 random val from a uniform dist, and if less than 0.2...
passengers <- passengers - 1 #subtract 1 from passengers (i.e. n-1)
newpass <- sample(0:2, 1, prob=c(0.5, 0.4, 0.1)) #take one random sample from 0,1,2, with probability weights 0.5, 0.4, 0.1, respectively
passengers <- passengers + newpass #add existing passengers to number of new passengers
}
passengers_after[i] <- passengers
if (passengers == 0) count <- count + 1 #if the number of passengers still equal zero by now, add 1 to the count
}
passenger_sample <- data.frame(passengers_before,passengers_after)
print(count/nreps)
Now, passenger_sample will be a data.frame with the number of rows equal to the number of iterations (e.g. 10,000), and it will have two columns: passengers_before and passengers_after.
Here's the first first handful of rows:
head(passenger_sample)
passengers_before passengers_after
1 0 2
2 0 4
3 0 4
4 0 4
5 0 1
6 0 2