7

Is there a way to run 2 different blocks of code at the same time. I have been looking at parallel packages within R and they all appear to be based on running the same function in a loop. I am looking for a way to run different functions at the same time (1 iteration of the loop). For example, I would like to create a model on a certain data object at the same time as creating another model on a different object. I could do this by starting another instance of R but would rather keep it all in the same script. Is this possible? I appreciate any advice.

John Richardson
  • 676
  • 8
  • 24

2 Answers2

3

You could try substituting/quoting the functions then evaluating them in parallel.

library(parallel)
ExpressionVect <- c(substitute(function1()), 
                substitute(function2()))

mclapply(ExpressionVect, eval, mc.cores= 2)

This allows the functions to be evaluated in parallel when they are independent functions

Jonno Bourne
  • 1,931
  • 1
  • 22
  • 45
0

You can use clusterMap, which is a parallel version of mapply. This assumes you want to fit the same type of model on each node (lm, glm, rpart, whatever).

clus <- makeCluster(2)
out <- clusterMap(clus, lm, formula=list(speed ~ dist, mpg ~ cyl + disp + hp),
                            data=list(cars, mtcars))
Hong Ooi
  • 56,353
  • 13
  • 134
  • 187
  • Thanks Hong, but I also have some more code that needs to run other than just model creation. I basically have two rather long functions that include model creation in each. Any ideas? – John Richardson Feb 03 '14 at 15:19