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

I would like to complete the set.seed () scope after a certain line in order to have real randomization for the rest of the code. Here is an example where 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 the suggestions, really!

+5
r random-seed
source share
3 answers

Just use the current system time to โ€œundoโ€ the seed by entering a new unique random seed:

 set.seed(Sys.time()) 

If you need better accuracy, consider sampling the timestamp in milliseconds (use the R system(..., intern = TRUE) function).

+10
source share

set.seed () only works for the next run. so what you want is already happening.

see this example

 set.seed(12) sample(1:15, 5) 

[1] 2 12 13 4 15

 sample(1:15, 5) # run the same code again you will see different results 

[1] 1 3 9 15 12

 set.seed(12)#set seed again to see first set of results sample(1:15, 5) 

[1] 2 12 13 4 15

+1
source share

set.seed () only works for the first line containing a random pattern, and will not affect the next following command. If you want it to work for other strings, you must call the set.seed function with the same seed parameter.

-one
source share

All Articles