首页 > 解决方案 > 带有自定义库的 package.install 无法加载包

问题描述

我正在尝试将具有依赖关系的 R 包安装自定义库位置。这是最小的示例脚本 ( req.R):

dir.create("r_packages")
install.packages("R.utils", lib="r_packages")
library("R.utils", character.only = TRUE, lib.loc="r_packages")

运行它Rscript(例如在r-base docker 容器中)显示,安装运行良好,但加载失败

输出缩短。全贴在这里

$ Rscript req.R
also installing the dependencies ‘R.oo’, ‘R.methodsS3’

[...]

* installing *source* package ‘R.methodsS3’ ...
[...]
* DONE (R.methodsS3)
* installing *source* package ‘R.oo’ ...
[...]
* DONE (R.oo)
* installing *source* package ‘R.utils’ ...
[...]
* DONE (R.utils)

The downloaded source packages are in
        ‘/tmp/RtmpU4nBhU/downloaded_packages’
Error: package ‘R.oo’ required by ‘R.utils’ could not be found
Execution halted

以相反的依赖顺序一一加载可以正常工作

$ cat req.R
dir.create("r_packages")
#install.packages("R.utils", lib="r_packages")
library("R.methodsS3", character.only = TRUE, lib.loc="r_packages")
library("R.oo", character.only = TRUE, lib.loc="r_packages")
library("R.utils", character.only = TRUE, lib.loc="r_packages")


$ Rscript req.R
Warning message:
In dir.create("r_packages") : 'r_packages' already exists
R.methodsS3 v1.7.1 (2016-02-15) successfully loaded. See ?R.methodsS3 for help.
R.oo v1.22.0 (2018-04-21) successfully loaded. See ?R.oo for help.

Attaching package: ‘R.oo’

The following objects are masked from ‘package:methods’:

    getClasses, getMethods

The following objects are masked from ‘package:base’:

    attach, detach, gc, load, save

R.utils v2.8.0 successfully loaded. See ?R.utils for help.

Attaching package: ‘R.utils’

The following object is masked from ‘package:utils’:

    timestamp

The following objects are masked from ‘package:base’:

    cat, commandArgs, getOption, inherits, isOpen, parse, warnings

有人暗示正确的方向吗?我究竟做错了什么?

标签: rinstall.packages

解决方案


经过一番研究,我发现,设置标准库路径.libPaths()解决了这个问题。显然,该library()函数不会将lib.loc参数传递给后续调用。

这是最终代码:

dir.create("r_packages")
.libPaths(c("r_packages"))
install.packages("R.utils", lib="r_packages")
library("R.utils", character.only = TRUE, lib.loc="r_packages")

推荐阅读