Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting seed locally (not globally) in R

I'd like to set seeds in R only locally (inside functions), but it seems that R sets seeds not only locally, but also globally. Here's a simple example of what I'm trying (not) to do.

myfunction <- function () {   set.seed(2) }  # now, whenever I run the two commands below I'll get the same answer myfunction() runif(1) 

So, my questions are: why does R set the seed globally and not only inside my function? And how I can make R to set the seed only inside my function?

like image 580
Manoel Galdino Avatar asked Jan 14 '13 18:01

Manoel Galdino


People also ask

Can you set seed for sample in R?

In R, we can set a random seed to make the output of our R code reproducible. By setting a specific seed, the random processes in our script always start at the same point and hence lead to the same result.

Do you only need to set seed once in R?

So the short answer to the question is: if you want to set a seed to create a reproducible process then do what you have done and set the seed once; however, you should not set the seed before every random draw because that will start the pseudo-random process again from the beginning.

How does setting a seed in R work?

The use of set. seed is to make sure that we get the same results for randomization. If we randomly select some observations for any task in R or in any statistical software it results in different values all the time and this happens because of randomization.

What is set seed 123 in R?

set seed (value) where value specifies the initial value of the random number seed. 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.


1 Answers

Something like this does it for me:

myfunction <- function () {   old <- .Random.seed   set.seed(2)   res <- runif(1)   .Random.seed <<- old   res } 

Or perhaps more elegantly:

myfunction <- function () {   old <- .Random.seed   on.exit( { .Random.seed <<- old } )   set.seed(2)   runif(1) } 

For example:

> myfunction() [1] 0.1848823 > runif(1) [1] 0.3472722 > myfunction() [1] 0.1848823 > runif(1) [1] 0.4887732 
like image 192
Romain Francois Avatar answered Sep 18 '22 04:09

Romain Francois