运行 命令行中的 Rscript 和加载包

Running Rscript in command line and loading packages

我有一个 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

非常感谢在 运行ning "Rscript" 期间提供有关如何加载包的任何帮助。

为了将来的参考,您可以使用函数 require 而不是 library 来避免此错误:require just returns 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")