foreach loop in R returns NA values for my array output

Viewed 137

I am trying to Apply foreach loop in R for one of my projects since for loop takes very long for output. The problem is foreach loops doesn't update memory and returns NA value. I found that this can be ruled out while creating matrix using the FBM function of bigstatsr package of R, but I have a code that deals with arrays and not 2D matrices. here is the code

for (z in 1:100){
ft <- array(NA,c(x,y,length(beta),r) #x, y, beta are defined



foreach (jj = 1:y)%:%
  foreach (r in 1:length(beta) %dopar% {
    model.1 <- bvar() #a random statitical model function 
    
    ft[,jj,,r] <- model.1$pred[,1,k] # model.1$pred is itself an array
    
  }
dimnames(ft)[[2]] <- cN

save(ft, file = paste0(foldername,"/", formatC(run, width=2, flag=0), ".RData"))
}

Now the problem is foreach loop returns just NA values for my ft array since it doesn't update the memory. is there any thing i can do to make it work. or some way where i can use the FBM function by changing my matrix into array.

1 Answers

I guess the part taking time is fitting the models.

So you can always return list(jj, r, ft[,jj,,r]) (or even just ft[,jj,,r]) and fill the array later.

all_res <- foreach (jj = 1:y) %:%
  foreach (r = 1:length(beta)) %dopar% {
    model.1 <- bvar() #a random statitical model function     
    model.1$pred[,1,k] # model.1$pred is itself an array    
  }

ft <- array(NA,c(x,y,length(beta),r) #x, y, beta are defined

for (jj in 1:y) 
  for (r in 1:length(beta))
    ft[,jj,,r] <- all_res[[jj]][[r]]
Related