Random Number Seed in R

When simulating any random numbers it is essential to set the random number seed. Setting the random number seed with set.seed() ensures reproducibility of the sequence of random numbers.

For example, you can generate 10 Normal random numbers with rnorm().

 

set.seed(1)
rnorm(10)

Output:

[1] -0.6264538 0.1836433 -0.8356286 1.5952808 0.3295078 -0.8204684 0.4874291 0.7383247 0.5757814 -0.3053884

Note that if you call rnorm() again you will of course get a different set of 10 random numbers.

rnorm(10)

Output:

[1] 1.51178117 0.38984324 -0.62124058 -2.21469989 1.12493092 -0.04493361 -0.01619026 0.94383621 0.82122120 0.59390132

If you want to reproduce the original set of random numbers, you can just reset the seed with set.seed()

set.seed(1)
rnorm(10)

Output:

[1] -0.6264538 0.1836433 -0.8356286 1.5952808 0.3295078 -0.8204684 0.4874291 0.7383247 0.5757814 -0.3053884

You should always set the random number seed when conducting a simulation! Otherwise, you will not be able to reconstruct the exact numbers that you produced in an analysis.

It is also possible to generate random numbers from other probability distributions like the Poisson. The Poisson distribution is commonly used to model data that come in the form of counts.

 

rpois(5, 10) # 5 numbers with a mean of 10
rpois(5, 20) # 5 numbers with a mean of 20

Output:

> rpois(5, 10)
[1] 14 11 8 2 8
> rpois(5, 20)
[1] 21 16 23 22 24

Generating Random Numbers

Random Sampling