R set.seed () scope

My R script calls subfunctions that contain set.seed (). What is the scope of set.seed ()? Will it also affect the main program that calls it?

More specific

# main program callsubfun() ... some statement ... sample.int(100,20) # sub function callsubfun <- function(x,y,...){ set.seed(100) ... do the work ... return(something) } 
+7
random r seed
source share
3 answers

set.seed really global. But look at the example from ?set.seed :

 ## If there is no seed, a "random" new one is created: rm(.Random.seed); runif(1); .Random.seed[1:6] 

This means that you can call rm(.Random.seed, envir=.GlobalEnv) either at the end of your function or after calling the function to separate the rest of the program from the call to set.seed in the function.

To see this in action, run the following code in two different R sessions. The outputs should be the same in both sessions. Then run the code again in two new R sessions using the rm line without commenting. You will see that the output in the two new sessions is now different, which indicates that calling the set.seed function in the function did not pass reproducibility to the main program.

 subfun <- function() { set.seed(100) rnorm(1) #rm(.Random.seed, envir=.GlobalEnv) } subfun() #[1] -0.5022 rnorm(1) # [1] 0.1315 
+7
source share

This is why you should NOT do this:

 > set.seed(100) > rnorm(1) [1] -0.5021924 > rnorm(1) [1] 0.1315312 > rand <- function() set.seed(100) > rand() > rnorm(1) [1] -0.5021924 # Ouch! 
+3
source share

BondedDust answer is OK, but not always Ouch!

You can use set.seed () to reproduce the algorithm. that is, everyone can reproduce your results.

I recommend you use set.seed if you want to share your code. For example, if you need help with stackoverflow, we could accurately reproduce your code.

 set.seed(123) rand<-rnorm(10) plot(density(rand)) 

If you use another seed, you get different results.

 set.seed(234) rand<-rnorm(10) plot(density(rand)) 

Both are correct, but it would be easier to help you if the seed were known. By the way, just use set.seed once in your routine, because you can generate a dependency in your random numbers. We want independent random numbers in the simulation.

-one
source share

All Articles