为什么 set.seed() 会影响 R 中的 sample()

rno*_*ian 5 random r sampling resampling

我一直认为set.seed()只让随机变量生成器(例如,rnorm)为任何特定的输入值集生成唯一的序列。

但是,我想知道,为什么当我们设置set.seed(), 然后函数sample()不能正确完成它的工作?

具体来说,鉴于下面的例子,有没有一种方法可以set.seed在之前使用,rnorm但如果多次运行,sample仍然会从中产生新的随机样本?rnormsample

这是一个R代码:

set.seed(123458)
x.y = rnorm(1e2)

sampled = sample(x = x.y, size = 20, replace = TRUE)

plot(sampled)
Run Code Online (Sandbox Code Playgroud)

the*_*ail 7

根据帮助文件在 ?set.seed

“如果使用 seed = NULL 调用,它会重新初始化(参见“注意”),就好像尚未设置种子一样。”

因此,由于rnormsample都受 影响set.seed(),您可以执行以下操作:

set.seed(639245)
rn <- rnorm(1e2)
set.seed(NULL)
sample(rn,5)
Run Code Online (Sandbox Code Playgroud)