6

I am currently using knitr along with R 3.0.2 and RStudio in order to produce a LaTeX report. My report is typed up as a .Rnw file, and compiled using the knit2pdf function.

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

Is this possible? If so, how can I refer to the R variable in the .tex document?

Berk U.
  • 7,018
  • 6
  • 44
  • 69

2 Answers2

6

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

At the line before the optional section starts, do

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

At the line after the optional section ends, do

<<endcomment, results='asis', echo=FALSE>>=
if(!CreateOptionalSection){
  cat("\\end{comment}")
}
@
fabians
  • 3,383
  • 23
  • 23
3

You can do it directly in R code in your .Rnw file, using cat to paste the section. Here is an example, when x > 0 it creates section 1, when x < 0 it 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

Carlos Cinelli
  • 11,354
  • 9
  • 43
  • 66
  • Would it be possible to extend this solution so that \Sexpr{x} was included in the text variable? Thank you. I posted a similar question about this here: http://stackoverflow.com/questions/32492667/if-else-statement-in-knitr-sweave-using-r-variable-as-conditional –  Sep 10 '15 at 03:30