set.seed() and Reproducibility
Ensure reproducible random number generation across runs with set.seed().
Why Reproducibility Matters
Random number generation is pseudo-random: a deterministic algorithm seeded by a starting value. Setting the seed makes your simulations reproducible — the same code always produces the same results, essential for debugging, publishing, and teaching.
# Without set.seed: different every run
runif(3) # e.g., 0.21, 0.57, 0.89 (changes each run)
runif(3) # different again!
# With set.seed: always identical
set.seed(42)
runif(3) # always: 0.9148060 0.9370754 0.2861395
set.seed(42) # reset seed
runif(3) # exactly the same three numbers again
cat('set.seed() is your reproducibility guarantee')set.seed() Mechanics
set.seed(n) initializes the random number generator (RNG) state. Any positive integer works. The seed determines the entire future sequence of random numbers until the seed is reset. Use a fixed number for reproducibility.
# Different seeds give different sequences
set.seed(1)
seq1 <- rnorm(5)
set.seed(99)
seq2 <- rnorm(5)
print(seq1)
print(seq2)
identical(seq1, seq2) # FALSE
# Same seed always gives same sequence
set.seed(1)
seq1_again <- rnorm(5)
identical(seq1, seq1_again) # TRUE
# Common seed choices
set.seed(123) # popular convention
set.seed(2024) # use year for temporal clarityAll lessons in this course
- set.seed() and Reproducibility
- Generating Random Distributions
- Monte Carlo Simulation Basics
- Bootstrap Resampling in R