Kirk Fogg Kirk Fogg - 2 months ago 16
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){
set.seed(i)
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

This works:

library (foreach)

fn<-function(i)
{
  set.seed(i)
  y <- rnorm(1)
  return(y)
}

x<-foreach(i=1:10) %do% fn(i)
print(x)