Running a Simulation Study - Solutions

Exercise A - (3 min)

Recall this code snippet from our earlier lecture on simulation:

dice_sum <- \() {
# Roll a pair of fair, six-sided dice and return their sum
  die1 <- sample(1:6, 1)
  die2 <- sample(1:6, 1)
  die1 + die2
}
sims <- map_dbl(1:10000, \(i) dice_sum())
  1. Use your new-found knowledge of purrr to explain line 7.
  2. Write a for loop to replace line 7.

Solution

The anonymous function \(i) dice_sum() has one argument: i. But this argument isn’t used in any way! Regardless of the value of i we simply call dice_sum(). This is just a sneaky way of getting map_dbl() to repeatedly call dice_sum() a total of 10000 times. It is equivalent to the following for() loop:

nreps <- 10000
sims <- rep(NA_real_, nreps)
for(i in seq_along(sims)) {
  sims[i] <- dice_sum()
}