Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I stop set.seed() after a specific line of code?

Tags:

I would like to end the scope of set.seed() after a specific line in order to have real randomization for the rest of the code. Here is an example in which I want set.seed() to work for "rnorm" (line 4), but not for "nrow" (line 9)

set.seed(2014) f<-function(x){0.5*x+2} datax<-1:100 datay<-f(datax)+rnorm(100,0,5) daten<-data.frame(datax,datay) model<-lm(datay~datax) plot(datax,datay) abline(model) a<-daten[sample(nrow(daten),20),] points(a,col="red",pch=16) modela<-lm(a$datay~a$datax) abline(modela, col="red") 

Thanks for suggestions, indeed!

like image 584
Clyde Frog Avatar asked Mar 29 '14 07:03

Clyde Frog


People also ask

Do I have to set seed everytime?

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 set seed() work in R?

The set. seed() function sets the starting number used to generate a sequence of random numbers – it ensures that you get the same result if you start with that same seed each time you run the same process.

What is set seed 1 in R?

What is to set seed in R? Setting a seed in R means to initialize a pseudorandom number generator. Most of the simulation methods in Statistics require the possibility to generate pseudorandom numbers that mimic the properties of independent generations of a uniform distribution in the interval ( 0 , 1 ) (0, 1) (0,1).


2 Answers

set.seed(NULL) 

See help documents - ?set.seed:

"If called with seed = NULL it re-initializes (see ‘Note’) as if no seed had yet been set."

like image 97
Carlton Chen Avatar answered Feb 17 '23 02:02

Carlton Chen


Simply use the current system time to "undo" the seed by introducing a new unique random seed:

set.seed(Sys.time()) 

If you need more precision, consider fetching the system timestamp by millisecond (use R's system(..., intern = TRUE) function).

like image 44
Robert Krzyzanowski Avatar answered Feb 17 '23 00:02

Robert Krzyzanowski