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?
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
RNGKind; you would normally not touch this in R),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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With