为什么set.seed()影响R中的sample() [英] Why set.seed() affect sample() in R
问题描述
我一直认为set.seed()
仅使随机变量生成器(例如rnorm
)为任何特定的一组输入值生成唯一的序列.
I always thought set.seed()
only makes random variable generators (e.g., rnorm
) to generate a unique sequence for any specific set of input values.
但是,我想知道为什么当我们设置set.seed()
时,功能sample()
不能正确执行其工作?
However, I'm wondering, why when we set the set.seed()
, then the function sample()
doesn't do its job correctly?
具体地说,给出以下示例,有一种方法可以在rnorm
之前使用set.seed
,但是如果rnorm
中产生新的随机样本>多次运行?
Specifically, given the below example, is there a way I can use set.seed
before the rnorm
but sample
would still produce new random samples from this rnorm
if sample
is run multiple times?
set.seed(123458)
x.y = rnorm(1e2)
sampled = sample(x = x.y, size = 20, replace = TRUE)
plot(sampled)
推荐答案
根据?set.seed
"如果使用seed = NULL进行调用,它将重新初始化(请参见注意"),就像没有 种子尚未确定."
"If called with seed = NULL it re-initializes (see ‘Note’) as if no seed had yet been set."
因此,由于rnorm
和sample
都受set.seed()
的影响,因此您可以执行以下操作:
So, since rnorm
and sample
are both affected by set.seed()
, you can do:
set.seed(639245)
rn <- rnorm(1e2)
set.seed(NULL)
sample(rn,5)
这篇关于为什么set.seed()影响R中的sample()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!