【发布时间】:2015-06-08 16:38:57
【问题描述】:
我有五个图像存储如下(其中“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-loop 或 .Rnw 文件中):
nPlots=1
plotName = "thePlot"
outDir = "results"
img <- readJPEG(paste(getwd(), "/", outDir , "/", plotName, "_", i, ".jpg", sep=""))
plot(img)
生成的图像看起来与我拥有的 .jpeg 图像不同(位于 currentDirectory/results/thePlot_1.jpg)
【问题讨论】:
-
尝试将
paste(...)包裹在\Sexpr{}中。 -
@AlexA.:感谢您的帮助。它似乎确实解决了这个问题,尽管 for 循环似乎仍然不能像我希望的那样工作。您对出现的这个新错误有什么建议吗?
-
我不认为使用
\For和\EndFor包含多个绘图是最好的方法。 (我实际上不认为你可以那样做。)我可能会做一个 R 块,如<<plots, echo = FALSE, fig = TRUE, figs.only = TRUE, results = hide>>(R 代码显示图)@。这将自动嵌入它们。 -
@AlexA。再次感谢。我现在正在按照您建议的方法进行尝试,但是遇到了一些奇怪的情况。我是否错过了将图像读入 R 代码的更简单的方法?谢谢。
-
嗯。这很奇怪......不幸的是,这不是我的专业领域,所以希望其他人很快会加入进来启发我们。
标签: r image for-loop sweave rnw