Specify package location in foreach

北慕城南 提交于 2019-12-11 09:39:27

问题


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?


回答1:


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.




回答2:


Hi here there is another solution:

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


来源:https://stackoverflow.com/questions/33503708/specify-package-location-in-foreach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!