set.seed()
for Reproducibility
Learn how to control randomness in R so your results are consistent, shareable, and scientifically reproducible every single time.
What is Randomness in R?
R has many functions that produce random output: generating random numbers, sampling from data, shuffling elements, and running simulations. Each time you call one, you get different results.
The Reproducibility Problem
Without a seed, running the same code twice produces different random outputs. This is a serious problem for science, homework, and debugging.
What is a Seed?
A seed is a starting number that initializes the pseudo-random number generator. Given the same seed, R's PRNG always produces the exact same sequence of "random" numbers.
The Core Rule
The integer 42 is arbitrary: you can use any whole number. What matters is that everyone uses the same seed to get the same results.
How PRNG Works Under the Hood
R's default PRNG is the Mersenne Twister algorithm. It maintains an internal state that advances with each random number generated. The seed sets the initial state.
With Seed vs. Without Seed
| With set.seed() | Without set.seed() | |
|---|---|---|
| Run 1 output | 0.914, 0.937, 0.286 | 0.288, 0.788, 0.409 |
| Run 2 output | 0.914, 0.937, 0.286 | 0.883, 0.940, 0.046 |
| Reproducible? | ✓ Yes, always | ✕ No, never |
| Debugging | Easy: same inputs | Hard: results vary |
| Collaboration | Share code + seed | Can't verify results |
How to Apply set.seed()
Example 1: Basic Reproducibility
Generate 5 random numbers from a normal distribution with a fixed seed.
Example 2: Reproducible Sampling
Randomly select 3 students from a class for a survey, reproducibly.
Example 3: Simulation Study
Simulate flipping a coin 1000 times and count heads. Reproducible seeds let you share exact simulation results.
Seeds Get Consumed
A common misconception: the seed does not persist across multiple random calls. Each call advances the PRNG state.
Order Matters
Inserting or removing any random call between the seed and your target operation changes the result.
Common Mistakes
Summary Reference
| Concept | Details |
|---|---|
| Syntax | set.seed(integer) |
| Seed value | Any integer (42, 123, 2024, etc.) |
| Scope | Affects all subsequent random calls until a new seed is set |
| Placement | Immediately before the random operation |
| Default PRNG | Mersenne Twister (R 3.6+) |
| Persistence | Consumed by random calls: must re-call to reset |
| Cross-platform | Same results on Windows, Mac, Linux (same R version) |
Question 1 of 5
What does set.seed() do in R?
Question 2 of 5
Code:
set.seed(10)
runif(1) # Call A
runif(1) # Call B
Will Call A and Call B produce the same number?
Question 3 of 5
Where should you place set.seed() in your script for best practice?
Question 4 of 5
Code:
set.seed(99)
x <- rnorm(5)
set.seed(99)
y <- rnorm(5)
What is the relationship between x and y?
Question 5 of 5
What is the name of R's default pseudo-random number generator algorithm?