I need to reset a random seed multiple times in a loop, because I have to call a function that will draw a particular value with a dedicated seed (not shown in my example). The suggested solution to set a truly random seed has been to call "rm(.Random.seed, envir=globalenv())". However, it actually causes that the same seed is set because the loop is processed so fast that the globalenv() returns the same value for multiple consecutive iterations of the loop.
In the code below, I am calling rm(.Random.seed, envir=globalenv()) each loop iteration. As can be seen, in the 100,000 random draws out of a pool of 1:100,000 integers, only 14,522 unique numbers are drawn. In contrast, if one were to sample 100,000 draws directly out of 100,000 with replacement, more than 63,000 unique values are drawn. The difference is due to rm(.Random.seed, envir=globalenv()) returning the same seed too many time because the loop is processed too fast.
Desired Code
T= 100000
values = vector(length = T)
for(i in 1:T)
{
values[i] = sample(1:T,1, replace = TRUE)
#some function that calls a seed and needs to be randomly reset to a new seed afterwards
rm(.Random.seed, envir=globalenv())
}
length(unique(values))
[1] 14522
counterfactual
length(unique(sample(1:T,T, replace = TRUE)))
[1] 63189
If I were able to reset a seed (assign a truly new random seed for each iteration), the number of unique values would be similar to the counterfactual number ~63,000
Aucun commentaire:
Enregistrer un commentaire