将for循环中的多个图像插入Sweave文档中

问题描述 投票:2回答:2

我有五个存储的图像,如下所示(其中“ 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中)

我存储了五张图像,如下所示(其中“ currentDirectory”是我从命令getwd()获得的结果):currentDirectory / results / thePlot_1.jpg currentDirectory / results / thePlot_2.jpg ...

r image for-loop sweave rnw
2个回答
0
投票

0
投票

对于任何可能尝试使用乳胶和编织图像循环的人,我都会进行绘图。像这样:

© www.soinside.com 2019 - 2024. All rights reserved.