Home > other >  Parallel Computing for nested for loop in R
Parallel Computing for nested for loop in R

Time:02-24

As I am trying to run the following code in R, it took a very long time to execute. Hence would like to check if I could use parallel programming to run this. I see online that people would convert the task to a function first. But not too sure how can i go about doing it.

holder = matrix(0, 1000, 20)

for (x in 1:1000) {
  end = x   99
  thedata = dataindataframe[x:end,]

  for (y in 1:20) {
    m = garchFit(~garch(1,1), data = thedata[,y], trace = FALSE)
    holder [x,y] = predict(m, 1)[,3]
  }
}

holder

If you could help write the code for parallel programming, that will be of great. Thank you!

CodePudding user response:

This is a pretty simple parallelization scenario.

Without a reproducible example I cannot guarantee this will work. However, this is how I would approach it, that is parallelizing the outermost loop.

library(doParallel)
library(foreach)
library(fGarch)

registerDoParallel(parallel::detectCores()-2) #Or set this to whatever is reasonable for your computer/server 

holder <- foreach(x=1:1000, .combine = "rbind", .packages='fGarch') %dopar% {
  end = x   99
  thedata = dataindataframe[x:end,]

  pred <- numeric(20L)
  for (y in 1:20) {
    m = garchFit(~garch(1,1), data = thedata[,y], trace = FALSE)
    pred[y] = predict(m, 1)[,3]
  }
  return(pred)
}

Some other resources:

  • Related