How to generate same random numbers in R

r

#1

I want to test my code in r but when ever I try to generate the numbers I am getting different numbers every time I want that I get same set of numbers.
for example
rnorm(5)
[1] -0.9558808 0.6193731 -0.2956910 -0.4956769 -1.0553607
rnorm(5)
[1] 1.0526602 0.3217464 -0.1587927 -0.3195149 0.7362737

I am calling rnorm two times and I am getting different result.I am not able to figure it out.


#2

Hi @sid100158,

This can be done in two ways.

  1. You save the first rnorm(5) output and use it again again, for saving it just use random <-rnorm(5), then use “random” list anywhere

  2. You can use set.seed option, it allows you to give the same random number every time. Please look at below code -
    set.seed(47)
    rnorm (5)

  • now if you want the same result again use the same thing
    set.seed (47)
    rnorm(5)

The output of both the result will be same. Hope this helps.

Regards,
Aayush