Here we show how to set seeds in R using the set.seed() function, in order to be able to reproduce outputs.

When R outputs are random or based on simulations, by setting seeds, we can reproduce the same results as often as we want.

The set.seed() function is from the "base" package.

1 Set Seed Before a Simulation or a Random Sampling

To be able to reproduce a simulation or a random sample we can do the following (for example, using a normal distribution sampling).

# Any number can be used, but here we use `123`
set.seed(123)
rnorm(5, 0, 1)
[1] -0.56047565 -0.23017749  1.55870831  0.07050839  0.12928774

We can enter the same seed as often as we want and the same result will be produced.

value = 123
set.seed(value)
rnorm(5, 0, 1)
[1] -0.56047565 -0.23017749  1.55870831  0.07050839  0.12928774

2 Set Seed Before Multiple Random Samplings

We can replicate multiple sampling too, provided the order of randomization does not change.

set.seed(1000)
rnorm(4, 0, 1)
[1] -0.44577826 -1.20585657  0.04112631  0.63938841
rnorm(6, 0, 1)
[1] -0.78655436 -0.38548930 -0.47586788  0.71975069 -0.01850562 -1.37311776

The same can be replicated provided we have rnorm(4, 0, 1) as the first randomization followed by rnorm(6, 0, 1) after setting the same seed.

set.seed(1000)
random1 = rnorm(4, 0, 1)
random1
[1] -0.44577826 -1.20585657  0.04112631  0.63938841
random2 = rnorm(6, 0, 1)
random2
[1] -0.78655436 -0.38548930 -0.47586788  0.71975069 -0.01850562 -1.37311776

3 Reset Seed

To reset seed, set the seed value as NULL.

set.seed(NULL)

Copyright © 2020 - 2024. All Rights Reserved by Stats Codes