简体   繁体   中英

Save multiple results of foreach loops in R

Suppose I have the following simple for loops for a simulation and OLS estimation:

set.seed (12345)
m <- rnorm(20, 0, 1)
n <- 10
b1 <- 0.5
b2 <- 2
model1_b <- matrix(nrow=n, ncol=2)
model2_b <- matrix(nrow=n, ncol=2)
error <- matrix(nrow=20, ncol=n)

for (a in 1:2){
 for (b in 1:4){

   x <- (m+a)/b

   for (r in 1:10){
     repeat {

       e <- rnorm(20, 0, 0.5) # the error term
       error[,r] <- e

       # OLS estimation of Model_1
       y=b1 + b2*x + e # the true model 1
       Model_1 <- lm (y~x)
       model1_b[r,]=Model_1$coef

       # OLS estimation of Model_2
       y=b1 + b2*(x^2) + e # the true model 2
       Model_2 <- lm (y~x)
       model2_b[r,]=Model_2$coef

       if (Model_1$coef[1]!=0 & Model_2$coef[1]!=0) {break}

     } # end of repeat{} loop
    } # end of for(r){} loop
   } # end of for(b){} loop
  } # end of for(a){} loop

  error
  model1_b
  model2_b

I want to convert these nested for loops into nested foreach loops, such that I could do parallel computing. As you can see that, data generated within the loops, such as error , model1_b , model2_b , are saved one by one in matrices that I defined before running the loop. My question is: how can I save these results in foreach loops? no matter in a list, data frame or matrix.

(Note: My actual model is much more complex, and the first (outer) and second loops are relatively small in size. But the third (inner) loop is quite large. Maybe I don't need nested foreach loops, and it's OK to parallelize only the inner loop. Really appreciate if you guys can teach me how to save the results on both situations (using three nested foreach loops and using foreach only on the inner loop).

concerning store results(error, model1_b and model2_b) in a foreach loop, the answer can be found at Saving multiple outputs of foreach dopar loop

and %dorng% might be used instead of using %dopar%.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM