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

2020-03-25 03:08发布

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)

2条回答
Anthone
2楼-- · 2020-03-25 03:42

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)
查看更多
男人必须洒脱
3楼-- · 2020-03-25 04:05

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)
查看更多
登录 后发表回答