我一直认为 set.seed() 只会让随机变量生成器(例如,rnorm)为任何特定的输入值集生成唯一的序列.>
然而,我想知道,为什么当我们设置 set.seed() 时,函数 sample() 不能正确地完成它的工作?
问题具体来说,给定下面的例子,有没有一种方法可以在 rnorm 之前使用 set.seed 但sample<如果多次运行 sample,/code> 仍会从此 rnorm 生成新的随机样本?
这是一个 R 代码:set.seed(123458)x.y = 范数(1e2)采样 = 样本(x = x.y,大小 = 20,替换 = TRUE)绘图(采样) 解决方案根据 ?set.seed
中的帮助文件"如果用seed = NULL调用它会重新初始化(见注意"),好像没有种子尚未设置."
所以,由于 rnorm 和 sample 都受 set.seed() 的影响,你可以这样做:
set.seed(639245)rn <- norm(1e2)set.seed(NULL)样本(rn,5)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.
However, I'm wondering, why when we set the set.seed(), then the function sample() doesn't do its job correctly?
QuestionSpecifically, 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?
Here is an R code: set.seed(123458) x.y = rnorm(1e2) sampled = sample(x = x.y, size = 20, replace = TRUE) plot(sampled)解决方案
As per the help file at ?set.seed
"If called with seed = NULL it re-initializes (see ‘Note’) as if no seed had yet been set."
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()
发布评论