Running Rscript in command line and loading packages

邮差的信 提交于 2019-12-11 02:45:03

问题


I have a foo.R file which contains

library("ggplot2")
cat("Its working")

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

Any help on how to load packages while running "Rscript" is much appreciated.


回答1:


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.




回答2:


Or you could use this,

# --------- 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")


来源:https://stackoverflow.com/questions/30893829/running-rscript-in-command-line-and-loading-packages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!