We load the mosaic package to simulate coin flips using a vector coin.

library(mosaic)
coin <- c("heads", "tails")

Computers can’t actually generate pure random numbers. Rather, they generate pseudorandom numbers: they are statistically indistinguishable from true randomness but are generated by an entirely deterministic process.

### Seed Values

The pseudorandom number generator works by taking in a seed value, which is a combination of values that we assume has no distinguishable pattern. Example: a seed value can be some numerical combination of

• Time of day
• Data
• Amount of space left on the hardrive
• Voltage measurements

The generator takes that seed value and then generates numbers that “look” random. The catch: if you give the random number generator the same seed value, it gives the same pseudorandom values.

### Example

Say a HW question asks you “Say you flip a coin 1000 times, how many heads do you observe?” You run the simulation and get:

sim_fair_coin <- resample(coin, size = 1000)
tally(~sim_fair_coin)

Say you run the simulation again. Chances are you won’t get the same results.

sim_fair_coin <- resample(coin, size = 1000)
tally(~sim_fair_coin)

When reporting the results in the write-up portion of your HW’s, you’ll have to change it every time!

### Setting the same seed value

There is a solution. You can get “replicable” pseudorandom results by manually setting the seed number. If you don’t manually set it, R uses the crazy scheme from the section “Seed Values”. Observe that you get the same number of heads in both the following simulations:

set.seed(76)
sim_fair_coin <- resample(coin, size = 1000)
tally(~sim_fair_coin)
set.seed(76)
sim_fair_coin <- resample(coin, size = 1000)
tally(~sim_fair_coin)

and then subsequent simulations without resetting the seed yields different values

sim_fair_coin <- resample(coin, size = 1000)
tally(~sim_fair_coin)

### Different seed values yield different results

But if you set a different seed value, you get different results

set.seed(76)
sim_fair_coin <- resample(coin, size = 1000)
tally(~sim_fair_coin)
set.seed(79)
sim_fair_coin <- resample(coin, size = 1000)
tally(~sim_fair_coin)

### Moral of the story

To get “replicable” random values, at the beginning of your .Rmd file, set the seed value to your favorite number just once in a grey R code block somewhere at the beginning of the file.