【问题标题】:Using Rscript with an .Rnw file AND commandArgs()将 Rscript 与 .Rnw 文件和 commandArgs() 一起使用
【发布时间】:2019-10-16 07:15:39
【问题描述】:

我有一个 .Rnw 文件,其中包含 R 代码块和 LaTeX 命令。到目前为止,我一直在Rstudio中开发和测试这段代码:点击“编译PDF”得到一些输出文件和生成的PDF文件。

我现在想使用 commandArgs() 给我的 .Rnw 一个参数:一个 YAML 文件。该文件包含脚本所需的各种参数。

给出一些上下文:

  • 我的 .Rnw 脚本是一个管道脚本,它被设计为尽可能“通用”。

  • 我的 .Rnw 脚本每次都需要一些参数 - 这些参数将在每个项目之间变化。为了提供这些参数,我目前(已经)使用 YAML 配置文件。这意味着我的 .Rnw 脚本做的第一件事就是导入 YAML 文件,然后它开始做事。

我的问题是:我可以同时使用“Rscript”、“commandArgs()”和 knitr 吗?我希望将一些 commandArgs() 添加到我的 .Rnw 脚本中,我将能够像这样运行所有内容(即在命令行上提供参数以提供 YAML 文件并编译 PDF):

Rscript script.Rnw params.yaml

但是,我收到有关“\”的错误,我强烈怀疑这与我使用 .Rnw 文件(其中的第一件事是 LaTeX 命令)有关。然后我在其他帖子上看到了潜在的解决方案,例如:

 Rscript -e "library(knitr); knit('script.Rnw')"
 pdflatex script.tex

但是,这也失败了——我想这并不奇怪,因为我没有给它我的配置 YAML 文件。

我意识到我的设计可能存在缺陷:通过同时使用 commandAgrs() 和 knitr,我让事情变得相当复杂。我也意识到 knitr 可能并不是真正设计用于为用作管道的脚本制作报告(至少这是我的印象)。我想使用它的原因是,对于每个项目,都可以生成一个包含所有结果的快速 PDF。

如果有任何建议,我将不胜感激。这是我的代码示例:

\documentclass[12pt, a4paper]{article}

\usepackage[utf8]{inputenc}
\usepackage{hyperref}
\hypersetup{
colorlinks   = true, %Colours links instead of ugly boxes
urlcolor     = blue, %Colour for external hyperlinks
linkcolor    = blue, %Colour of internal links
citecolor   = blue %Colour of citations
 }
\usepackage{caption}
\setlength{\parindent}{0pt}
\usepackage{authblk}
\usepackage[nomarkers, nolists]{endfloat} %Positions figures at the end of the document and add no list of names (requires that chunk have fig.cap option)
\usepackage{soul} % Allows underline lines to be broken (use \ul{} instead of \underline{})

\usepackage{helvet} %Set up Arial as font
\renewcommand{\familydefault}{\sfdefault}

\newcommand{\Rfunction}[1]{{\texttt{#1}}}
\newcommand{\Rpackage}[1]{{\textit{#1}}}

\title{\textbf{Report}}
\author{Author}
\date{\today}



\begin{document}

\maketitle

\begingroup
\hypersetup{linkcolor=black} % force independent link colours in table of contents
\tableofcontents
\endgroup

\begingroup
\hypersetup{linkcolor=black} % force independent link colours in list of figures
\listoffigures
\endgroup



\newpage
\section{Introduction} 
This report blah blah blah

\newpage
\section{Results}

<<importing-lib, echo=FALSE, message=FALSE, cache=TRUE>>=

###################################################
# Obtain command-line YAML file and set directory #
###################################################

#!/usr/bin/env Rscript
args= commandArgs(trailingOnly=TRUE)

if (length(args) == 0) {
 stop("this script requires a configuration file (.yaml) as input")

 } else if (length(args) > 1) {
  stop("this script requires only one input: a configuration file (.yaml)")

}

params <-  yaml.load_file(args[1])

setwd(params$workdir)

if (dir.exists(file.path(params$workdir, "results")) == FALSE) {
  dir.create(file.path(params$workdir, "results","edgeR"), recursive = TRUE)
  dir.create(file.path(params$workdir, "results", "gsea", "input_files"), recursive = TRUE)
}

print("Hello!")
@

\end{document}

【问题讨论】:

  • 您走在正确的轨道上,但您必须将配置脚本与 .Rnw 文件分开,即您必须从 importing-lib 块中获取代码并将其放入自己的 . R 文件,将knitr 命令添加到该文件,并使用Rscript 调用它。
  • @Alexis 谢谢,我按照你的建议做了。我已经用我发现的两种方法给出了答案。不确定 100% 哪个最好,但我认为您建议的方法更好。

标签: r knitr rscript commandargument


【解决方案1】:

好的,所以我找到了 2 种可行的方法:

方法一:使用命令行knitr()和pdflatex

在这种情况下,一切仍然是一个脚本(称为 script.Rnw),但看起来像这样:

\documentclass[12pt, a4paper]{article}

\usepackage[utf8]{inputenc}
\usepackage{hyperref}
\hypersetup{
colorlinks   = true, %Colours links instead of ugly boxes
urlcolor     = blue, %Colour for external hyperlinks
linkcolor    = blue, %Colour of internal links
citecolor   = blue %Colour of citations
 }
\usepackage{caption}
\setlength{\parindent}{0pt}
\usepackage{authblk}
\usepackage[nomarkers, nolists]{endfloat} %Positions figures at the end of the document and add no list of names (requires that chunk have fig.cap option)
\usepackage{soul} % Allows underline lines to be broken (use \ul{} instead of \underline{})

\usepackage{helvet} %Set up Arial as font
\renewcommand{\familydefault}{\sfdefault}

\newcommand{\Rfunction}[1]{{\texttt{#1}}}
\newcommand{\Rpackage}[1]{{\textit{#1}}}

\title{\textbf{Test report}}
\date{\today}



\begin{document}

\maketitle

\begingroup
\hypersetup{linkcolor=black} % force independent link colours in table of contents
\tableofcontents
\endgroup

\begingroup
\hypersetup{linkcolor=black} % force independent link colours in list of figures
\listoffigures
\endgroup



\newpage
\section{Introduction} 
This is the introduction.

\newpage
\section{Results}

This is the results.

<<importing-lib, echo=FALSE, message=FALSE>>=

###################################################
# Obtain command-line YAML file and set directory #
###################################################

#!/usr/bin/env Rscript
args= commandArgs(trailingOnly=TRUE)

if (length(args) == 0) {
  stop("this script requires a configuration file (.yaml) as input")

  # } else if (length(args) > 1) {
  # stop("this script requires only one input: a configuration file (.yaml)")

}

library(yaml)
params <- yaml.load_file(args[1])

dir <- getwd()

if (dir.exists(file.path(dir, "results")) == FALSE) {
  dir.create(file.path(dir, "results","part1"), recursive = TRUE)
  dir.create(file.path(dir, "results", "part2", "input_files"), recursive = TRUE)
}

print("Hello!")
print(params$project)
@



\newpage
\section{End}

This is the end!

\end{document}

运行管道:

Rscript -e "library(knitr); knit('script.Rnw')" params.yaml && pdflatex script.tex

方法2:将代码分离为.Rnw文件和.R启动文件

script.Rnw 如下所示:

\documentclass[12pt, a4paper]{article}

\usepackage[utf8]{inputenc}
\usepackage{hyperref}
\hypersetup{
colorlinks   = true, %Colours links instead of ugly boxes
urlcolor     = blue, %Colour for external hyperlinks
linkcolor    = blue, %Colour of internal links
citecolor   = blue %Colour of citations
 }
\usepackage{caption}
\setlength{\parindent}{0pt}
\usepackage{authblk}
\usepackage[nomarkers, nolists]{endfloat} %Positions figures at the end of the document and add no list of names (requires that chunk have fig.cap option)
\usepackage{soul} % Allows underline lines to be broken (use \ul{} instead of \underline{})

\usepackage{helvet} %Set up Arial as font
\renewcommand{\familydefault}{\sfdefault}

\newcommand{\Rfunction}[1]{{\texttt{#1}}}
\newcommand{\Rpackage}[1]{{\textit{#1}}}

\title{\textbf{Test report}}
\date{\today}



\begin{document}

\maketitle

\begingroup
\hypersetup{linkcolor=black} % force independent link colours in table of contents
\tableofcontents
\endgroup

\begingroup
\hypersetup{linkcolor=black} % force independent link colours in list of figures
\listoffigures
\endgroup



\newpage
\section{Introduction} 
This is the introduction.

\newpage
\section{Results}

This is the results.

<<first-chunk, echo=FALSE, message=FALSE>>=

print("Hello!")
print(params$project)
@



\newpage
\section{End}

This is the end!

\end{document}

launch.R 脚本如下所示:

#!/usr/bin/env Rscript

library(yaml)
library(knitr)

args= commandArgs(trailingOnly=TRUE)

if (length(args) == 0) {
  stop("this script requires a configuration file (.yaml) as input")

  # } else if (length(args) > 1) {
  # stop("this script requires only one input: a configuration file (.yaml)")

}

params <- yaml.load_file(args[1])

dir <- getwd()

if (dir.exists(file.path(dir, "results")) == FALSE) {
  dir.create(file.path(dir, "results","edgeR"), recursive = TRUE)
  dir.create(file.path(dir, "results", "gsea", "input_files"), recursive = TRUE)
}

knit2pdf('script.Rnw')

运行脚本:

Rscript launch.R params.yaml

方法之间的一个区别:方法 1 生成更多文件(*tex、*toc、*out、*log、*aux),大概是因为它在技术上是 2 个命令。方法2只生成一个.tex和一个.pdf文件。

【讨论】:

    猜你喜欢
    • 2014-05-08
    • 2013-03-16
    • 1970-01-01
    • 2013-04-16
    • 2018-06-06
    • 1970-01-01
    • 2015-12-11
    • 2010-09-19
    • 2017-10-04
    相关资源
    最近更新 更多