R启动时.Rprofile调用install.packages报找不到函数的问题
问题:.Rprofile自动加载时找不到install.packages函数
我测试用的.Rprofile代码如下:
message("~/.Rprofile starting") options(repos="https://cran.microsoft.com/") if (!require("data.table")) install.packages("data.table") message("~/.Rprofile ending")
使用R --vanilla启动后执行source("~/.Rprofile")可正常运行,但以标准方式启动R时,自动加载该.Rprofile会报错:
~/.Rprofile starting Loading required package: data.table Error: could not find function "install.packages" In addition: Warning message: In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE, : there is no package called ‘data.table’ >
我推测这和.Rprofile嵌入的特定启动机制有关,想知道是否存在需要在.Rprofile执行完成后才加载的库?尝试通过.libPaths()调试,但未理清函数中.lib.loc的来源。
解答
这是因为R启动时,.Rprofile的执行时机早于utils包的加载——install.packages是utils包中的函数,标准启动流程里,utils包会在.Rprofile执行完毕后才自动加载。而用R --vanilla启动后再手动source,此时utils已经加载完成,所以能正常运行。
解决办法有两个:
- 显式加载
utils包:在调用install.packages前添加library(utils); - 用全限定名调用函数:把
install.packages改成utils::install.packages,无需提前加载包。
修改后的.Rprofile示例(全限定名方式):
message("~/.Rprofile starting") options(repos="https://cran.microsoft.com/") if (!require("data.table")) utils::install.packages("data.table") message("~/.Rprofile ending")
内容的提问来源于stack exchange,提问作者ivo Welch
相关产品推荐
相关产品推荐

