Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting seed in R

Tags:

r

If I want to generate several random variables in R, all using the same seed, do I have to set the seed every time? For example, should I write:

set.seed(123456) 
x = runif(1000,0,1)  

set.seed(123456) 
e = rnorm(1000,0,1)  

set.seed(123456) 
y = 4 + 0.3*x + e

or just set the seed once and define all the variables?

like image 598
luisdiego24 Avatar asked Dec 30 '25 09:12

luisdiego24


1 Answers

It’s recommended to only set the random seed once.

From then on you can use it to generate random numbers freely.

Now, to reproduce the exact same sequence of random numbers you need to

  1. Seed the generator with the same seed,
  2. Use the same random number generator (via RNGKind; you would normally not touch this in R),
  3. perform the exact same sequence of calls to functions that consume random numbers.

That last point is important: Setting the same random seed but performing a different sequence of calls, will yield different random numbers. For instance:

set.seed(12345)
runif(10)
rnorm(10)

set.seed(12345)
runif(5)
rnorm(10)

… this will yield different random numbers for the rnorm calls.

like image 108
Konrad Rudolph Avatar answered Jan 01 '26 05:01

Konrad Rudolph