Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set.seed with R 2.15.2

My understanding is that using set.seed ensures reproducibility but this is not the case with the following R code in R 2.15.2. Am I missing something here?

set.seed(12345)
rnorm(5)
[1]  0.5855288  0.7094660 -0.1093033 -0.4534972  0.6058875
 rnorm(5)
[1] -1.8179560  0.6300986 -0.2761841 -0.2841597 -0.9193220
like image 770
MYaseen208 Avatar asked Jan 17 '13 13:01

MYaseen208


2 Answers

set.seed() reinitializes the random number generator.

set.seed(12345)
rnorm(5)
[1]  0.5855288  0.7094660 -0.1093033 -0.4534972  0.6058875

set.seed(12345)
rnorm(5)
[1]  0.5855288  0.7094660 -0.1093033 -0.4534972  0.6058875

set.seed(12345)
rnorm(5)
[1]  0.5855288  0.7094660 -0.1093033 -0.4534972  0.6058875
like image 157
Stephan Kolassa Avatar answered Oct 05 '22 11:10

Stephan Kolassa


Any call that uses the random number generator will change the current seed, even if you've manually set it with set.seed.

set.seed(1)
x <- .Random.seed # get the current seed
runif(10) # uses random number generator, so changes current seed
y <- .Random.seed
identical(x, y) # FALSE

As @StephanKolassa demonstrates, you'd have to reset the seed before each use of the random number generator to guarantee that it uses the same one each time.

like image 24
Matthew Plourde Avatar answered Oct 05 '22 11:10

Matthew Plourde