samedi 23 février 2019

How can I replicate specific random draws in loops of different size?

I am struggling to understand how to replicate results from earlier work. I set a seed before I ran a loop with runs X, where some randomness happens in each iteration of the loop. I am now running a smaller loop with runs Y trying to replicate results in only a couple of iterations of that bigger loop (i.e., Y < X). I can't figure out how to do this. Any help much appreciated. MWE is below.

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




Aucun commentaire:

Enregistrer un commentaire