2

I want to run the following code:

library(parallel)

cl <- makeCluster(detectCores())
requires <- c("fUnitRoots","fGarch")

for(req in requires) {
  clusterEvalQ(cl,require(req))
}

list1 <- clusterApply(cl,1:10,function(i) {
  x <- rnorm(100)
  y <- rnorm(100)
  m <- lm(y~x)
  res <- resid(m)
  t <- adfTest(res) ## this function is in {fUnitRoots}
  return(t@test$statistic)
})

stopCluster(cl)

However, fUnitRoots package is not loaded in any node. It is probably because clusterEvalQ(cl,expr) where expr is an expression. require(req) is treated as an expression where req is not regarded as the iterator variable as a character.

How should I refine the code to make it work?

1 Answer 1

4

The "character.only" option is useful when calling "require" in this situation. Also, I would use "clusterCall" instead of "clusterEvalQ" to allow the package names to be passed as an argument to a worker function:

clusterCall(cl, function(pkgs) {
  for (req in pkgs) {
    require(req, character.only=TRUE)
  }
}, c("fUnitRoots","fGarch"))

This is also a bit more efficient since it loads all of the packages in a single cluster operation.

You can verify that the packages were correctly loaded using:

clusterEvalQ(cl, search())
Sign up to request clarification or add additional context in comments.

1 Comment

I tried your clusterCall code but it all returns FALSE for me. May you please offer some help as I need to load a large amount of library into each cluster node? Also, how do we remove some packages from every cluster nodes? I also wonder if clusterEvalQ(cl, library(dplyr)) helps put the library(dplyr) into each cluster node, as that was the only option working for me (and I tried clusterExport(cl, library(dplyr))` and clusterCall(cl, library(dplyr)...All I got were messages object: forcats not found)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.