Weird behavior of using set.seed multiple times

Viewed 2156

I came up with a strange result when doing my homework in R, can anyone explain to me what's going on?

The instruction told me to set seed 1 to keep consistency.

At first, I set seed(1) twice

set.seed(1)
x <- rnorm(100, mean = 0, sd = 1)
set.seed(1)
epsilon <- rnorm(100, mean = 0, sd = 0.25)
y <- 0.5 * x + epsilon -1
plot(x,y,main = "Scatter plot between X and Y", xlab = "X", ylab = "Y")

I get scatter plot like this: The plot with two set seed

After I only use one set seed the code is:

set.seed(1)
x <- rnorm(100, mean = 0, sd = 1)
epsilon <- rnorm(100, mean = 0, sd = 0.25)
y <- 0.5 * x + epsilon -1
plot(x,y,main = "Scatter plot between X and Y", xlab = "X", ylab = "Y")

The plot became reasonable: The plot with one set seed

Can anyone explain to me why two results are different by adding an extra "set.seed(1)"?

2 Answers

Why the results were different - When set.seed is set once and run twice -

set.seed(123)
runif(3)
[1] 0.2875775 0.7883051 0.4089769
runif(3)
[1] 0.8830174 0.9404673 0.0455565

Whereas when set.seed is set again the results are -

set.seed(123)
runif(6)
[1] 0.2875775 0.7883051 0.4089769 0.8830174 0.9404673 0.0455565

So, when the seed is set only once, the program uses the next set of available numbers for generating the next set of random numbers

Related