To perform a calculation or simulation several times, use the replicate
function. Requires each trial to be independent and identical.
But if formula in ith iteration depends on i, can’t use replicate. Instead, use for
loops
If we don’t know at outset how many times to run experiment, we use while
loops.
Suppose we want to add up first 20 integers.
current_sum <- 0
for (i in 1:20){
current_sum <- current_sum + i
print( c(i, current_sum) )
}
## [1] 1 1
## [1] 2 3
## [1] 3 6
## [1] 4 10
## [1] 5 15
## [1] 6 21
## [1] 7 28
## [1] 8 36
## [1] 9 45
## [1] 10 55
## [1] 11 66
## [1] 12 78
## [1] 13 91
## [1] 14 105
## [1] 15 120
## [1] 16 136
## [1] 17 153
## [1] 18 171
## [1] 19 190
## [1] 20 210
Suppose we want to figure out how many times we need to multiply 2 by itself to exceed 1000
my_product <- 1
steps <- 0
while (my_product <= 1000) {
my_product <- my_product*2
steps <- steps+1
print(c(steps, my_product))
}
## [1] 1 2
## [1] 2 4
## [1] 3 8
## [1] 4 16
## [1] 5 32
## [1] 6 64
## [1] 7 128
## [1] 8 256
## [1] 9 512
## [1] 10 1024
Suppose we roll a pair of dice repeatedly. What is the probability that a sum of 7 appears before a sum of 9?
# to roll two dice and add
sum( sample(1:6, size = 2, replace = T) )
## [1] 7
seven_before_nine <- function(){
my_sum <- 0
steps <- 0
while(my_sum != 7 & my_sum !=9){
my_sum <- sum( sample(1:6, size = 2, replace = T) )
steps <- steps+1
}
return(my_sum)
}
Now, run function 10,000 times
n_times <- 10^4
sum( replicate(n_times, seven_before_nine()) == 7 ) / n_times
## [1] 0.5997