7

Using R, knitr, and beamer, I have created a pdf that contains a graph for each school in our district. I read in each graph using the \includegraphics command within a /foreach loop. I want to create a unique section name for each school using the R-variable 'school'. I want this section name to appear in the left hand Table of Contents. Relevant code is below. Thanks.

\foreach \i in {1,...,\Sexpr{length(school)}} {%
\section{\Sexpr{school[i]}}    %%% Here is where it is breaking down
\begin{frame}
    \includegraphics[width=\textwidth,height=\textheight,keepaspectratio]{plot_\i.pdf}
\end{frame}%
  }
6

You use variable \i, which is TeX variable. The problem is, R knows nothing about it. Since R runs before TeX, your loop never reaches R.

Instead you can make the loop in R. The R code should produce the TeX code. You need to output results in the asis mode, and suppress the code itself.

This works for me:

<<echo=FALSE,results='asis'>>=
for (i in 1:length(school)) {  
  cat(paste("\\section{",school[i],"}\n",sep=""))
  cat("\\begin{frame}\n")
  cat(paste("\\includegraphics[width=\\textwidth,",
            "height=\\textheight,keepaspectratio]{plot_",
            i, ".pdf}\n", sep=""))
  cat("\\end{frame}\n")
}
@ 

Each cat forms a TeX line which is included in the TeX file; chunk options make the code invisible to TeX and the results sent 'as is'

|improve this answer|||||
  • 1
    That is correct. People often mix R programming with LaTeX programming, which is not possible in knitr. R/knitr knows nothing about LaTeX programs. – Yihui Xie May 20 '14 at 16:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.