在命令行上运行 r 代码时出现包错误 [英] Package error when running r code on command line

查看:59
本文介绍了在命令行上运行 r 代码时出现包错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我运行了一些包含这部分的代码:

I have some code that I run that includes this part:

if (!require("yaml")) {
  install.packages("yaml") 
  library("yaml")
}

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

When I run in it rstudio, everything runs seamlessly and there are no bugs. However, when I try running my code on the command line, I get this error:

$ 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

推荐答案

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

RStudio sets a default repository when you call install.packages from within RStudio. When you run the script via the command line, you have to tell R which repository to use (or set a global default repository).

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

You can easily fix this problem by telling R to use your favorite repository.

例如,如果您想使用 RStudio 的包存储库,请在 install.packages 调用中设置 repos="http://cran.rstudio.com/".

For example, if you want to use RStudio's package repository, set repos="http://cran.rstudio.com/" inside the install.packages call.

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

这应该有效!

这篇关于在命令行上运行 r 代码时出现包错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆