Random sampling is useful, but examples and tests need repeatable output. set.seed fixes the random sequence.

Program

Play the script to see the same sample produce the same total every run.

set_seed.R
Replay: real traced execution (multi-file project)
set.seed(7)
draws <- sample(1:10, 3)
total <- sum(draws)
cat(total, "\n", sep = "")
  1. random seed ← 7

    1set.seed(7)2draws <- sample(1:10, 3)
    values this step7random seed
  2. draws ← 10, 3, 7

    1set.seed(7)2draws <- sample(1:10, 3)3total <- sum(draws)
    values this step10, 3, 7draws
  3. total ← 20

    2draws <- sample(1:10, 3)3total <- sum(draws)4cat(total, "\n", sep = "")
    values this step20total10, 3, 7draws
  4. cat(total, " ", sep = "")

    3total <- sum(draws)4cat(total, "\n", sep = "")
    output20
    values this step20total
set.seed `set.seed(7)` makes later random operations repeatable.
sample `sample(1:10, 3)` chooses three values.
reproducibility A fixed seed helps examples and tests produce stable results.