R set.seed() with foreach

时间:2016-10-20 18:53:29

标签: r seed

I am trying to reproduce some results with no luck. Lets say I have the following in R:

x=rep(NaN,5)
for (i in 1:5) { 
set.seed(i)
X=runif(10)
x[i]=mean(X)
}

Suppose I now need to reproduce the 3rd iteration. Then:

set.seed(3)
runif(10)

by doing this I get the same results. THE PROBLEM begins when I try to parallelize my loop using foreach. I read that the doRNG package can solve the problem, so I have the following code:

set.seed(123)    
y=foreach(i=1:5) %dorng% {
X=runif(10)
x=mean(X)
return(x)
}

Which returns not only the estimated means but also the sequence of random seeds as an attribute:

attr(y, "rng")

## [[1]]
## [1]   407  642048078  81368183  -2093158836  506506973  1421492218  -19063881517
## [[2]]
## [1]   407  1340772676  -1389246211  -999053355  -953732024  1888105061  2010658538

And so on for the 5 replications.

How can I replicate the 3rd iteration? Thanks a lot for your time and help.

0 个答案:

没有答案