我有一个foo。包含 R 文件
library("ggplot2")
cat("Its working")
我正在尝试使用 Rscript 命令通过命令行运行 foo.r Rscript --default-packages=ggplot2 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"时加载包的任何帮助。
对于将来的引用,您可以使用函数require
而不是library
来避免此错误: require
只返回 FALSE 并在包未安装时引发警告,而不是抛出错误。因此,您可以按如下方式进行构造:
if(!require(ggplot2)){install.packages("ggplot2")}
它的作用是尝试加载包,如果未安装,则安装它。
或者你可以使用它,
# --------- 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")