How to specify the location of R packages in foreach( ... , .packages="pkg") %dopar%
My "pkg" was installed somewhere else, how could I tell foreach where to find the package?
foreach(i = 1:2,.packages="pkg") %dopar% { ... }
This give me error message:
wor开发者_如何转开发ker initialization failed: there is no package called 'pkg'
Thank you for your help.
Another approach would be to distribute the .libPaths
to all workers before you call foreach
:
library(foreach)
library(doParallel)
#setup parallel backend to use 8 processors
cl<-makeCluster(8)
registerDoParallel(cl)
# pass libPath to workers, NOTE THIS LINE
clusterCall(cl, function(x) .libPaths(x), .libPaths())
parallelResults <- foreach(i = 1:42, .combine = rbind) %dopar% {
# do your stuff
}
You could use the .libPaths()
function to set a library path in a running session.
Otherwise the startup files such as ~/.Renviron
can help, see the ?Startup
.
Lastly, if you use foreach
to run of different machines, you need to take care of the library path on each of the machines.
you can specify the libPaths inside the function
foreach(i = 1:2) %dopar% { .libPaths("your_location_to_pkg") library("pkg") ... }
精彩评论