如果我想在 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)
还是只设置一次种子并定义所有变量?
建议只设置一次随机种子。
从此您可以使用它自由生成随机数。
现在,要重现完全相同的随机数序列,您需要
RNGKind;你通常不会在 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)
Run Code Online (Sandbox Code Playgroud)
… this will yield different random numbers for the rnorm calls.