在 R 中设置种子

lui*_*o24 3 r

如果我想在 R 中生成多个随机变量,都使用相同的种子,我是否必须每次都设置种子?例如,我应该写:

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
Run Code Online (Sandbox Code Playgroud)

还是只设置一次种子并定义所有变量?

Kon*_*lph 5

建议只设置一次随机种子。

从此您可以使用它自由生成随机数。

现在,要重现完全相同的随机数序列,您需要

  1. 用相同的种子为生成器播种,
  2. 使用相同的随机数生成器(通过RNGKind;你通常不会在 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)
Run Code Online (Sandbox Code Playgroud)

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