首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在命令行中运行Rscript并加载包

在命令行中运行Rscript并加载包
EN

Stack Overflow用户
提问于 2015-06-17 13:59:47
回答 2查看 7.1K关注 0票数 2

我有一个foo.R文件,其中包含

代码语言:javascript
运行
复制
library("ggplot2")
cat("Its working")

我试图使用Rscript命令Rscript --default-packages=ggplot2 foo.R通过命令行运行foo.r,这给了我以下错误:

代码语言:javascript
运行
复制
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“时加载包的帮助都是非常感谢的。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-06-22 07:52:11

对于以后的引用,您可以使用函数require而不是library来避免此错误:如果没有安装包而不是抛出错误,require只会返回FALSE并引发警告。因此,您可以按以下方式进行构造:

代码语言:javascript
运行
复制
if(!require(ggplot2)){install.packages("ggplot2")}

它所做的是尝试加载软件包,如果没有安装,则安装它。

票数 1
EN

Stack Overflow用户

发布于 2018-04-25 17:34:33

或者你可以用这个,

代码语言:javascript
运行
复制
# --------- 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")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30893829

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档