Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R set.seed() 's scope

Tags:

random

r

seed

My R script calls sub-functions which contains set.seed(). What is the scope of the set.seed()? Will it also affect to main program that calls it?

More specificly

# main program
callsubfun()

... some statement ...

sample.int(100,20)



# sub function
callsubfun <- function(x,y,...){
   set.seed(100)
   ... do the work ...
   return(something)
}
like image 233
lolibility Avatar asked Aug 26 '14 18:08

lolibility


People also ask

What does set seed () do in R?

The set. seed() function in R is used to create reproducible results when writing code that involves creating variables that take on random values. By using the set. seed() function, you guarantee that the same random values are produced each time you run the code.

How do you set a seed value in R?

Syntax: set.seed(123) In the above line,123 is set as the random number value. The main point of using the seed is to be able to reproduce a particular sequence of 'random' numbers. and sed(n) reproduces random numbers results by seed. For more information for set.

Do you have to set seed everytime in R?

Using the same seed every time is not a good idea. If you use the same seed every time, you get the same sequence of pseudo-random numbers every time, and therefore your numbers are not pseudo-random anymore. Selecting a different seed every time is good practice.

What package is set seed in R?

set. seed in the simEd package allows the user to simultaneously set the initial seed for both the stats and simEd variate generators.


1 Answers

set.seed is indeed global. But note this from the example in ?set.seed:

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

This means you can call rm(.Random.seed, envir=.GlobalEnv) either at the end of your function or after you call the function to decouple 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 re-run the code again in two new R sessions with the rm line uncommented. You'll see the output in the two new sessions now differ, indicating that the call to set.seed in the function hasn't transferred the 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
like image 110
Matthew Plourde Avatar answered Sep 27 '22 21:09

Matthew Plourde