Save multiple results of foreach loops in R -
suppose have following simple for loops simulation , 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) (a in 1:2){ (b in 1:4){ x <- (m+a)/b (r in 1:10){ repeat { e <- rnorm(20, 0, 0.5) # error term error[,r] <- e # ols estimation of model_1 y=b1 + b2*x + e # 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 # 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 convert these nested for loops nested foreach loops, such parallel computing. can see that, data generated within loops, such error, model1_b, model2_b, saved 1 one in matrices defined before running loop. question is: how can save these results in foreach loops? no matter in list, data frame or matrix.
(note: actual model more complex, , first (outer) , second loops relatively small in size. third (inner) loop quite large. maybe don't need nested foreach loops, , it's ok parallelize inner loop. appreciate if guys can teach me how save results on both situations (using 3 nested foreach loops , using foreach on inner loop).
concerning store results(error, model1_b , model2_b) in foreach loop, answer can found @ saving multiple outputs of foreach dopar loop
and %dorng% might used instead of using %dopar%.
Comments
Post a Comment