I have five images stored as follows (where "currentDirectory" is the result I get from the command 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
I am trying to write a .Rnw script in Rstudio that will create the .tex file that I can then run pdflatex on to have a .pdf file containing these five images. Below is what I have tried:
\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}
For which I receive several errors:
Line 25: Undefined control sequence. Line 29: Missing $ inserted. Line 29: LaTeX Error: File `paste(getwd(), "/", outDir , "/", plotName, "_", i, sep="")' not found. Line 29: Missing $ inserted. Line 30: Undefined control sequence.
Any help greatly appreciated!
EDIT 1: I took into account Alex A.'s advice, and changed the section to include \Sexpr{} expressions as follows:
\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}
However, I now receive an error:
object 'i' not found
I tried changing the condition in the for loop to also include \Sexpr{} as in:
\FOR{\Sexpr{i in 1:5}}
But this gets me the error:
Unexpected 'in'
Any help is appreciated!
EDIT 2:
I tried taking into account advice to simply put the for-loop and image-insertion into Rcode. So, I tried to use the jpeg library and its readJPEG method, as shown below:
<<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}
Unfortunately, this still leads to the error:
unexpected 'in'
Also, when I run the below code alone (not in the for-loop or .Rnw file):
nPlots=1
plotName = "thePlot"
outDir = "results"
img <- readJPEG(paste(getwd(), "/", outDir , "/", plotName, "_", i, ".jpg", sep=""))
plot(img)
The image that generates looks different than the .jpeg image that I have (located in currentDirectory/results/thePlot_1.jpg)