Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

This tutorial describes how to integrate computable R code (and outputs) in a LaTeX documents in a such a way that a single file can generate two (or more) PDF files. This trick is particularly useful for creating worksheets for R courses.

A very small introduction to integrating R code in LaTeX files

R code is easily embedded in LaTeX documents using Sweave. Using Sweave is easy: you create a standard LaTeX file with the extension `.Rnw` and you can include R code chunks using special delimiters:

When the file is compiled (the best way to do it is to rely on the R package knitr under a RStudio environment because the production and compilation of Sweave files are integrated in a very handy manner), the R chunks are evaluated and the results (screen prints and figures) directly included in a `.tex` which is generated and can be itself compiled to obtain a PDF files including comments, R code and results. R chunks can include various options such as a chunk’s name, `cache` (to cache the results from one compilation), `echo` (to show/hide the R code), `results` (to specify how the results must be printed or even if they must be printed)…

A very small introduction to producing different PDF files from a single LaTeX file

I have been using different tricks for creating worksheets with a teacher/student versions (including or excluding the solutions) for a while. These include in particular:

• the use of LaTeX package comment: this package can print/hide some specific parts of a LaTeX document during compilation at will. This is done by using the commands
 ```includecomment{prof} excludecomment{etud}```

which, respectively, include/exclude the text written between

 ```begin{prof} teacher's version end{prof}```

and

 ```begin{etud} students' version end{etud}```

Unfortunately, none of these two solutions work combined with R chunks in Sweave files because of the way the R chunks are embedded in special environments in the output LaTeX file.

Solution to combine both needs

To combine both needs, a simple solution consists in using direct TeX script. A variable `version` is first defined, like when the ifthenelse package is used:

 `defversion{1}`

In our example, this variable can take two values: 1 (teacher version) and 0 (student version). Teacher specific text is included after the `if` command testing the value of `version`:

 ```if version1 emph{This is the teacher's version...} fi```

and similarly for the student specific text. A complete example (in which I included several tricks with LaTeX, Sweave files and chunk options) is provided at the end of this tutorial, which can be compiled to give this document for students and this document for the teacher.

conditionalSweave.Rnw