简体   繁体   English

R:set.seed在除去种子后产生相同的结果

[英]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 . 我想在R v.3.5.0for周期内生成随机序列。 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. 之后,我重新运行相同的脚本,并期望在会话中运行rm(.Random.seed, envir=globalenv())后重置种子。因此,将获得不同的结果。

But the reality is different - I receive exact the same list even after removal of .Random.seed from globalenv() . 但是实际情况有所不同-即使从.Random.seed globalenv()删除了.Random.seed之后,我仍然收到完全相同的列表。 Please, see the screen attached with exact sequence of commands: Sequence of commands 请查看附带确切命令顺序的屏幕:命令顺序

I'm really confused by such behaviour of set.seed. 我真的对set.seed的这种行为感到困惑。

My question is: 我的问题是:

1) Is such behaviour of set.seed normal? 1)set.seed的这种行为是否正常?

2) How to reset seed if rm(.Random.seed, envir=globalenv()) do not work? 2)如果rm(.Random.seed, envir=globalenv())如何重置种子?

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())来针对随机行为,所以为什么不从代码中完全删除set.seed

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. 无需在我们的代码中设置set.seed

I created workaround which based on usage of Sys.time() as a seed. 我基于Sys.time()作为种子创建了解决方法。 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. 但是,尽管如此,我需要添加Sys.sleep(1)因为如果该周期中的操作持续少于1秒,则此解决方案将不起作用。 I beleive that this is just workaround and the main question is still opened. 我相信这只是解决方法,主要问题仍然悬而未决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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