How to write an if-then statement in LaTeX using the value of the R variable in knitr / Sweave

I am currently using knitr with R 3.0.2 and RStudio to create a LaTeX report. My report prints as a .Rnw file and compiled using the knit2pdf function.

I would like to use if-then wording in LaTeX to create a separate section, but use the if-then condition of the value of a variable from R (let's call it CreateOptionalSection ).

Is it possible? If so, how can I access the R variable in a .tex document?

+6
source share
2 answers

Add \usepackage{comment} to the preamble of your latex file.

In the line before starting the optional section, do

 <<startcomment, results='asis', echo=FALSE>>= if(!CreateOptionalSection){ cat("\\begin{comment}") } @ 

In the line after the end of the section is optional

 <<endcomment, results='asis', echo=FALSE>>= if(!CreateOptionalSection){ cat("\\end{comment}") } @ 
+6
source

You can do this directly in the R code in your .Rnw file, using cat to insert this section. Here is an example when x > 0 creates section 1 , when x < 0 creates section 2 :

 \documentclass{article} \begin{document} <<condition, include=FALSE, echo=FALSE>>= x<- rnorm(1) if(x>0){ text <- "\\section{Section 1} This is new section 1" }else{ text <- "\\section{Section 2} This is new section 2" } @ Testing the code: the result of x (which here was \Sexpr{x}) will determine the section. <<print, results='asis', echo=FALSE>>= cat(text) @ \end{document} 

This will give you: enter image description here

+3
source

All Articles