← Back to R Course | Chapter 9: Statistics | Lesson 6 of 7

set.seed()

set.seed fixes the starting point of R's random choices so you get the same random picks each time. It is like shuffling a deck the very same way for everyone.

In this page:

  1. set.seed()
Syntax
r
set.seed(seed_number)
sample(x, size)

set.seed()

set.seed(n) initializes R's random number generator to a fixed, known starting state, making subsequent "random" operations like sample() or rnorm() reproducible across runs.

Without it, each run produces different random results. Setting a seed is essential for sharing reproducible analysis and for testing code that involves randomness.

Note: Always call set.seed() before any random operation in code you want others to be able to reproduce exactly.

Example: set.seed()

markup
set.seed(123)
print(sample(1:100, 5))

set.seed(123)
print(sample(1:100, 5))  # identical output, same seed
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Calling set.seed() after the random numbers are already drawn, so it has no effect on them.
  2. Setting the seed once at the top and expecting every later call to repeat, when the sequence continues after each draw.
  3. Using a seed and then assuming the numbers are truly random, when they are reproducible pseudo-random numbers.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.