我有一个包含
的foo.R文件library("ggplot2")
cat("Its working")
我正在尝试使用Rscript命令Rscript --default-packages=ggplot2 foo.R
通过命令行运行foo.r并且它给了我以下错误:
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"非常感谢。
答案 0 :(得分:1)
对于将来的引用,您可以使用函数require
而不是library
来避免此错误:require
只返回FALSE并在未安装软件包时引发警告而不是抛出错误错误。因此,您可以按如下方式进行构造:
if(!require(ggplot2)){install.packages("ggplot2")}
它的作用是尝试加载软件包,如果没有安装,则安装它。
答案 1 :(得分:0)
或者你可以使用它,
# --------- Helper Functions ------------ #
# Ref: https://gist.github.com/smithdanielle/9913897
# check.packages function: install and load multiple R packages.
# Check to see if packages are installed. Install them if they are not, then load them into the R session.
check.packages <- function (pkg) {
print("Installing required packages, please wait...")
new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
if (length(new.pkg)) {
install.packages(new.pkg, dependencies = TRUE)
}
sapply(pkg, library, character.only = TRUE)
}
# Usage example
# packages<-c("ggplot2", "afex", "ez", "Hmisc", "pander", "plyr")
# check.packages(packages)
check.packages("tidyverse")