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

2020-03-25 03:46发布

问题:

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)