Trevor Nederlof
Trevor Nederlof

Reputation: 2716

Specify package location in foreach

I am installing a package to a particular directory and then loading in the library using:

library(CustomPackage, lib.loc = "R_Libs")

Then when using foreach I am having trouble figuring out how to load this one package from that custom location "R_Libs".

foreach(i=(1:100), .packages=c("lubridate","CustomPackage")) %dopar% {
some code here...
}

Any ideas how to force that one package to be read from the "R_Libs" directory?

Upvotes: 3

Views: 1412

Answers (2)

Fraca
Fraca

Reputation: 21

Hi here there is another solution:

foreach(i=(1:100), .packages=c("lubridate")) %dopar%{ .libPaths("R_Libs") library("CustomPackage")  some code here... }

Upvotes: 2

Jianyu
Jianyu

Reputation: 31

Modifying library paths in R console is meaningless.

> library(doParallel)
> library(foreach)
> cl = makeCluster(detectCores() - 1)
> registerDoParallel(cl)
> getDoParWorkers()
[1] 3
> .libPaths()
[1] "D:/Program Files/R/R-3.2.3/library"
> .libPaths(c(.libPaths(), "C:/"))
> .libPaths()
[1] "D:/Program Files/R/R-3.2.3/library" "C:/"   

Inside foreach, the library paths are still the default:

> tmp = foreach(j = 1:2) %dopar% {.libPaths()}
> tmp
[[1]]
[1] "D:/Program Files/R/R-3.2.3/library"

[[2]]
[1] "D:/Program Files/R/R-3.2.3/library"

Though I'm not sure how exactly foreach works, but the idea is to start several new Rscripts. In each new Rscript, library paths will be the default ones specified in Rprofile.site.

So the most convenient way is to add paths in Rprofile.site under D:\Program Files\R\R-3.2.3\etc\

Another way is to load the library by hand, i.e.

tmp = foreach(j = 1:2) %dopar% {
          library(xxx, lib.loc = /xxx/xx)
          ...
      }

This is more flexible, especially when one cannot access Rprofile.site.

Upvotes: 3

Related Questions