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:
Syntax
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()
set.seed(123)
print(sample(1:100, 5))
set.seed(123)
print(sample(1:100, 5)) # identical output, same seed
Login to try C/C++/Java/PHP code in the editor
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
- Calling
set.seed()after the random numbers are already drawn, so it has no effect on them. - Setting the seed once at the top and expecting every later call to repeat, when the sequence continues after each draw.
- 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: