Question

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!

Was it helpful?

Solution 2

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).

OTHER TIPS

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."

set.seed() only works for the next execution. 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

set.seed() just works for the first line containing randomly sample, and will not influence the next following command. If you want it to work for the other lines, you must call the set.seed function with the same "seed"-the parameter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top