将 for-loop 中的多个图像插入到 Sweave 文档中

Insert multiple images in for-loop into Sweave Document

我有五个图像存储如下(其中 "currentDirectory" 是我从命令 getwd() 得到的结果):

currentDirectory/results/thePlot_1.jpg
currentDirectory/results/thePlot_2.jpg
currentDirectory/results/thePlot_3.jpg
currentDirectory/results/thePlot_4.jpg
currentDirectory/results/thePlot_5.jpg

我正在尝试在 Rstudio 中编写一个 .Rnw 脚本,该脚本将创建 .tex 文件,然后我可以 运行 pdflatex 获得包含这五个图像的 .pdf 文件。以下是我尝试过的:

\documentclass{article}
\usepackage{float, hyperref}
\usepackage[margin=1in]{geometry}
\usepackage{graphicx}
\usepackage{hyperref}
\usepackage{caption}
\usepackage{algorithm}
\usepackage{algorithmic}

\begin{document}
\SweaveOpts{concordance=TRUE}

\author{myName}
\title{myTitle}

\maketitle

<<options, echo=FALSE>>=
library(knitr)
  opts_chunk$set(cache=TRUE)
@

\section*{mySection}

\FOR{i in 1:5}
nPlots=i
plotName = "thePlot"
outDir = "results"
\includegraphics{paste(getwd(), "/", outDir , "/", plotName, "_", i, sep="")}
\ENDFOR

\end{document}

为此我收到了几个错误:

第 25 行:未定义的控制序列。 第 29 行:缺少插入的 $。 第 29 行:LaTeX 错误:找不到文件 `paste(getwd(), "/", outDir , "/", plotName, "_", i, sep="")'。 第 29 行:缺少插入的 $。 第 30 行:未定义的控制序列。

非常感谢任何帮助!

编辑 1:我考虑了 Alex A. 的建议,并将该部分更改为包含 \Sexpr{} 表达式,如下所示:

\FOR{i in 1:5}
\Sexpr{nPlots=i}
\Sexpr{plotName = "thePlot"}
\Sexpr{outDir = "results"}
\includegraphics{\Sexpr{paste(getwd(), "/", outDir , "/", plotName, "_", i, sep="")}}
\ENDFOR

\end{document}

但是,我现在收到一个错误:

object 'i' not found

我尝试更改 for 循环中的条件以包括 \Sexpr{},如:

\FOR{\Sexpr{i in 1:5}}

但这让我犯了错误:

Unexpected 'in'

感谢任何帮助!

编辑 2:

我尝试考虑将 for 循环和图像插入简单地放入 Rcode 中的建议。于是,我尝试使用jpeg库及其readJPEG方法,如下图:

<<echo=FALSE>>==
library(jpeg)
@

<<plots, echo = FALSE, fig = TRUE, figs.only = TRUE, results = hide>>=
for (i in 1:5){
  nPlots=i
  plotName = "thePlot"
  outDir = "results"

  img <- readJPEG(paste(getwd(), "/", outDir , "/", plotName, "_", i, ".jpg", sep=""))
  plot(img)
}
@

\end{document}

不幸的是,这仍然会导致错误:

unexpected 'in'

此外,当我单独 运行 下面的代码时(不在 for 循环或 .Rnw 文件中):

  nPlots=1
  plotName = "thePlot"
  outDir = "results"

  img <- readJPEG(paste(getwd(), "/", outDir , "/", plotName, "_", i, ".jpg", sep=""))
  plot(img)

生成的图像看起来与我拥有的 .jpeg 图像不同(位于 currentDirectory/results/thePlot_1.jpg)

来自the Sweave Manual

A.7 Creating several figures from one figure chunk does not work

要么手动保存绘图并使用 LaTeX 插入它们(按照 Sweave 手册的建议),要么切换到 knitr。我会推荐后者。

对于可能尝试使用乳胶和 knitr 图像循环的任何人,我都会为情节做这件事,例如。像这样:

<<echo=F, cache=T,cache.rebuild=T, results='asis' >>=

pictures <- c(pathtoimage1, pathtoimage2, pathtoimage3)   

plots <- ""
for(pic in pictures){
plots <- c(plots,paste("\includegraphics[width=0.5\linewidth]{",pic,"}",sep=""))
}
cat(plots)

@

我相信 results='asis' 可以解决问题。但我不是专家。这在循环中轻松地为我创建了一个块中的数百个图。

干杯

秘诀是在 cat 函数中使用粘贴。示例:

<<echo=F, cache=T,cache.rebuild=T, results='asis'>>=

for(i in c(1:100) {

    cat(paste("ok\\\")

}

@