简体   繁体   中英

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}"

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} 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM