Kirk Fogg Kirk Fogg - 1 year ago 102
R Question

Use set.seed() with foreach() in R

I am currently running a simulation using a for loop in R, but want to switch over to a foreach loop since it is faster. I use set.seed() in the for loop, and would like to use this again with foreach so I can obtain identical results.

For example, suppose I have

x <- c()
for (i in 1:10){
x[i] <- rnorm(1)

How can I do this same thing using foreach? I don't think this works:

x <- foreach(i = 1:10, ...) %dopar% {set.seed(i) ... }

Answer Source

This works:

library (foreach)

  y <- rnorm(1)

x<-foreach(i=1:10) %do% fn(i)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download