01 / 20

set.seed()
for Reproducibility

Learn how to control randomness in R so your results are consistent, shareable, and scientifically reproducible every single time.

R Programming

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.

runif()
Random uniform numbers between 0 and 1
rnorm()
Random numbers from a normal distribution
sample()
Random selection from a set of values

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.

# Run 1 runif(3)
Output (Run 1)
[1] 0.2875775 0.7883051 0.4089769
# Run 2 (same code!) runif(3)
Output (Run 2)
[1] 0.8830174 0.9404673 0.0455565

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.

Seed: 42 PRNG Algorithm (Mersenne Twister) 0.9148060 0.9370754 0.2861395 INPUT OUTPUT (always same) Same seed → Same sequence every time

The Core Rule

set.seed(42) runif(3)
Output (always)
[1] 0.9148060 0.9370754 0.2861395

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.

State 0 (from seed) → 0.914 State 1 (advanced) → 0.937 State 2 (advanced) → 0.286 State 3 ... ... Each random call advances the state: the sequence is deterministic Reset seed → Reset state → Replay the same sequence

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()

1
Choose any integer as your seed value (e.g., 42, 123, 2024).
2
Place set.seed(n) immediately before the random operation. Not at the top of the file: right before the call.
3
Run both lines together (seed + random call). If you run other random code in between, the state will advance.
4
Document the seed in comments or reports so others can reproduce your results.
5
Re-call set.seed() each time you need a fresh reproducible block. The seed is consumed by random operations.

Example 1: Basic Reproducibility

Generate 5 random numbers from a normal distribution with a fixed seed.

set.seed(123) x <- rnorm(5) print(x)
Output
[1] -0.5604756 -0.2301775 1.5587083 0.0705084 0.1292877

Example 2: Reproducible Sampling

Randomly select 3 students from a class for a survey, reproducibly.

students <- c("Alice", "Bob", "Carol", "David", "Eve", "Frank") set.seed(7) chosen <- sample(students, 3) print(chosen)
Output
[1] "Carol" "Eve" "Frank"

Example 3: Simulation Study

Simulate flipping a coin 1000 times and count heads. Reproducible seeds let you share exact simulation results.

set.seed(2024) flips <- sample(c("H", "T"), 1000, replace = TRUE) heads <- sum(flips == "H") cat("Heads:", heads, "\n")
Output
Heads: 497

Seeds Get Consumed

A common misconception: the seed does not persist across multiple random calls. Each call advances the PRNG state.

set.seed(42) runif(1) # → 0.9148060 runif(1) # → 0.9370754 (NOT 0.914 again!) # To reset, call set.seed() again: set.seed(42) runif(1) # → 0.9148060 (back to start!)

Order Matters

Inserting or removing any random call between the seed and your target operation changes the result.

# Version A set.seed(42) a <- rnorm(1) # → 1.3710 # Version B (extra call inserted) set.seed(42) runif(1) # consumes a state b <- rnorm(1) # → different from a!
seed(42) rnorm(1) = 1.3710 VERSION A seed(42) runif(1) rnorm(1) = different! VERSION B

Common Mistakes

✕ Seed at Top of File Only
Placing set.seed() once at line 1 and expecting all random calls throughout the script to be individually reproducible. Each call advances the state.
✕ Running Lines Out of Order
In RStudio, running code chunks out of order (or re-running just one line) changes the PRNG state and breaks reproducibility.
✕ Forgetting to Re-Seed
Expecting the same result from a second random call without calling set.seed() again. The first call already consumed the initial state.

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

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

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?