在命令行上运行r代码时出现包错误

kng*_*kng 35 r rstudio

我有一些我运行的代码包括这部分:

if (!require("yaml")) {
  install.packages("yaml") 
  library("yaml")
}
Run Code Online (Sandbox Code Playgroud)

当我在它中运行rstudio时,一切都无缝运行,没有错误.但是,当我尝试在命令行上运行我的代码时,我收到此错误:

$ Rscript.exe file.R
Loading required package: yaml
Installing package(s) into ‘/usr/lib/R/site-library’
(as ‘lib’ is unspecified)
Error in contrib.url(repos, type) :
  trying to use CRAN without setting a mirror
Calls: install.packages -> grep -> contrib.url
In addition: Warning message:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE,  :
  there is no package called ‘yaml’
Execution halted
Run Code Online (Sandbox Code Playgroud)

ial*_*alm 53

install.packages从RStudio内部调用时,RStudio设置默认存储库.当您通过命令行运行脚本时,您必须告诉R使用哪个存储库(或设置全局默认存储库).

您可以通过告诉R使用您喜欢的存储库轻松解决此问题.

例如,如果要使用RStudio的软件包存储库,请repos="http://cran.rstudio.com/"install.packages调用内部进行设置.

if (!require("yaml")) {
  install.packages("yaml", repos="http://cran.rstudio.com/") 
  library("yaml")
}
Run Code Online (Sandbox Code Playgroud)

这应该工作!