问题描述
我有一个foo.R文件,其中包含
I have a foo.R file which contains
library("ggplot2")
cat("Its working")
我正在尝试使用Rscript命令Rscript --default-packages=ggplot2 foo.R
通过命令行运行foo.r,它给了我以下错误:
I am trying to run foo.r via the command line using the Rscript commandRscript --default-packages=ggplot2 foo.R
and it is giving me the following error:
1: In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE, :
there is no package called ‘ggplot2’
2: package ‘ggplot2’ in options("defaultPackages") was not found
Error in library("ggplot2") : there is no package called ‘ggplot2’
Execution halted
非常感谢在运行"Rscript"时如何加载软件包的帮助.
Any help on how to load packages while running "Rscript" is much appreciated.
推荐答案
对于以后的引用,您可以使用函数require
而不是library
来避免此错误:require
仅返回FALSE并在警告提示时发出警告.未安装软件包,而是抛出错误.因此,您可以进行如下构造:
For future references, you could use function require
instead of library
to avoid this error: require
just returns FALSE and raises a warning if the package is not installed instead of throwing an error. You can therefore do a construct as follows:
if(!require(ggplot2)){install.packages("ggplot2")}
它所做的是尝试加载程序包,如果未安装,则将其安装.
What it does is trying to load the package and, if it is not installed, installs it.
这篇关于在命令行中运行Rscript并加载程序包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!