Why set.seed() affect sample() in R

社会主义新天地 提交于 2020-02-14 10:55:11

问题


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?

Question

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?

Here is an R code:

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

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

plot(sampled)

回答1:


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)



回答2:


Instead of resetting the seed with NULL, I think it makes more sense to save the current state and restore it.

x <- .Random.seed
set.seed(639245)
rn <- rnorm(1e2)
.Random.seed <- x
sample(rn,5)


来源:https://stackoverflow.com/questions/44013535/why-set-seed-affect-sample-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!