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!
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.
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 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).
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."
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With