28

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!

Clyde Frog
  • 483
  • 1
  • 6
  • 15

4 Answers4

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

Carlton Chen
  • 615
  • 5
  • 9
22

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

Community
  • 1
  • 1
Robert Krzyzanowski
  • 9,294
  • 28
  • 24
9

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

Akshay Kadidal
  • 515
  • 1
  • 7
  • 15
  • 12
    Actually no. if you run `set.seed(12)`, it starts some kind of loop of seeds. The second `sample` call will be identical all the time. Ex: Run once `set.seed(12)`, `s1a <- sample(1:15, 5)`, then `s2a <- sample(1:15, 5)`. then run `set.seed(12)`, `s1b <- sample(1:15, 5)`, then `s2b <- sample(1:15, 5)` and you'll have `identical(s1a, s1b)==TRUE` and `identical(s2a, s2b)==TRUE`. This is also true for all subsequent sample calls. – Bastien Oct 09 '19 at 18:30
-2

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.

Keru
  • 15
  • 2