Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a latex section title from the R code using knitr?

I am trying to produce a simulation report in Latex with knitR. My R code has a loop on products and generate a graph for each products. I want to include a section title for each loop iteration. I used resuls='asis' and tried to print the section title in the loop as in the code chunk below:

<<looptest, echo=FALSE, results='asis', warning=FALSE>>=
for (product in c("prod 1","prod 2")){
    print(paste("\\section{",product,"}", sep=""))
}
@

The issue is that I get this in the latex output:

[1] "\\section{prod 1}"
[1] "\\section{prod 2}"
like image 709
Paul Rougieux Avatar asked Mar 22 '23 22:03

Paul Rougieux


2 Answers

Thomas suggested me to post this as an answer. The solution is to use cat() instead of print()

<<looptest, echo=FALSE, results='asis', warning=FALSE>>= 
for (product in c("prod 1","prod 2")){ 
cat(paste("\\section{",product,"}", sep="")) }
@

Has the correct latex output:

\section{prod 1} 
\section{prod 2} 
like image 117
Paul Rougieux Avatar answered Mar 25 '23 12:03

Paul Rougieux


If you are looping through something to generate sections/chapters dynamically, I suggest use the loop functionality by knit_child. See the code from knitr-examples on GitHub.

like image 39
lcn Avatar answered Mar 25 '23 11:03

lcn