如何在不同大小的循环中复制特定的随机抽取?

问题描述 投票:2回答:1

我正在努力理解如何复制早期工作的结果。我在运行带有运行X的循环之前设置了一个种子,其中在循环的每次迭代中都会发生一些随机性。我现在正在运行一个较小的循环,其中运行Y试图仅在该较大循环的几次迭代中复制结果(即,Y <X)。我无法弄清楚如何做到这一点。任何帮助非常感谢。 MWE在下面。

set.seed(23) 
big_loop<-sapply(1:5,function(i) {
  saveRDS(.Random.seed,paste0("run_",i,".RDS"))
  sample(letters,1)
}) 

#I want to replicate the random letter draws on runs 2 and 3 of the big_loop

#I understand why this doesn't work
set.seed(23)
small_loop<-sapply(2:3,function(i) {
  sample(letters,1)
})

#but I'm not sure why this doesn't work.
#how can I make it match runs 2 and 3 of the big loop?
set.seed(23)
small_loop2<-sapply(2:3,function(i) {
  .Random.seed<-readRDS(paste0("run_",i,".RDS"))
  sample(letters,1)
})

#i want this to be false
identical(big_loop[1:2],small_loop) #true
identical(big_loop[1:2],small_loop2) #true

#I want these to be true
identical(big_loop[2:3],small_loop) #false
identical(big_loop[2:3],small_loop2) #false
r random
1个回答
3
投票

R使用来自全局环境的.Random.seed,所以你必须在那里分配它:在函数环境中分配它将不起作用(如你所见)。

small_loop2<-sapply(2:3,function(i) {
   assign(".Random.seed",readRDS(paste0("run_",i,".RDS")),
         envir=.GlobalEnv)
  sample(letters,1)
})
small_loop2
## [1] "f" "i"
big_loop
## [1] "o" "f" "i" "s" "v"

另一个稍微方便的解决方案是在每次运行中按顺序设置种子:

big_loop<-sapply(1:5,function(i) {
  set.seed(22+i)
  sample(letters,1)
}) 
small_loop<-sapply(2:3,function(i) {
  set.seed(22+i)
  sample(letters,1)
})

通过这种方式,您可以重现结果,而无需移动.Random.seed周围的笨重内容......

推荐顺序种子here;显然SQL RAND()not reliable when seeded with sequential values,但我不认为这是R的生成器的问题......

© www.soinside.com 2019 - 2024. All rights reserved.