简体   繁体   中英

R: set.seed produces the same result after seed removal

Background. I want to generate random sequences within a for cycle in R v.3.5.0 . To do this I use the code like bellow:

rm(.Random.seed, envir=globalenv())
some_list = list()
for (iter in 1:3) {
  set.seed(iter)
  some_list[[iter]] = sample(1:10)
}
some_list

This code returns me a list like this:

> some_list
[[1]]
 [1]  3  4  5  7  2  8  9  6 10  1
[[2]]
 [1]  2  7  5 10  6  8  1  3  4  9
[[3]]
 [1]  2  8  4  3  9  6  1  5 10  7

After that I'm rerunning the same script, and expect to have the seed to be reset after running rm(.Random.seed, envir=globalenv()) within session, hence get different result.

But the reality is different - I receive exact the same list even after removal of .Random.seed from globalenv() . Please, see the screen attached with exact sequence of commands: Sequence of commands

I'm really confused by such behaviour of set.seed.

My question is:

1) Is such behaviour of set.seed normal?

2) How to reset seed if rm(.Random.seed, envir=globalenv()) do not work?

Thanks in advance.

It seems like you are aiming for random behaviour with the call to rm(.Random.seed, envir=globalenv()) , so why not just remove the set.seed from your code altogether?

rm(.Random.seed, envir=globalenv())
some_list = list()
for (iter in 1:3) {
  some_list[[iter]] = sample(1:10)
}
some_list

The above produces different results each time you run it. There is no need to have set.seed in our code.

I created workaround which based on usage of Sys.time() as a seed. Here is a code:

some_list = list()
for (iter in 1:3) {
  set.seed(as.numeric(Sys.time()))
  some_list[[iter]] = sample(1:10)
  Sys.sleep(1)
}
some_list

But, neverthless, I needed to add Sys.sleep(1) because this solution does not work if operation in the cycle lasts less than 1 second. I beleive that this is just workaround and the main question is still opened.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM