<- \() {
dice_sum # Roll a pair of fair, six-sided dice and return their sum
<- sample(1:6, 1)
die1 <- sample(1:6, 1)
die2 + die2
die1
}<- map_dbl(1:10000, \(i) dice_sum()) sims
Running a Simulation Study - Solutions
Exercise A - (3 min)
Recall this code snippet from our earlier lecture on simulation:
- Use your new-found knowledge of
purrr
to explain line 7. - 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:
<- 10000
nreps <- rep(NA_real_, nreps)
sims for(i in seq_along(sims)) {
<- dice_sum()
sims[i] }