6.12 For hardcore LaTeX users (*)

R Markdown is certainly not the best possible document format for authoring or typesetting documents. Simplicity is both its advantage and disadvantage. LaTeX is much more powerful than Markdown in terms of typesetting at the price of more commands to be typed. If typesetting is of much higher priority to you and you are comfortable with using all kinds of LaTeX commands and environments, you can just use pure LaTeX code instead of Markdown to write the whole document.

The knitr package supports a variety of source document formats, including but not limited to R Markdown. Below is an example of intermingling R code with pure LaTeX code:

\documentclass{article}
\usepackage[T1]{fontenc}

\begin{document}

Here is a code chunk.

<<foo, fig.height=4>>=
1 + 1
par(mar = c(4, 4, .2, .2))
plot(rnorm(100))
@

You can also write inline expressions, e.g. $\pi=\Sexpr{pi}$,
and \Sexpr{1.9910214e28} is a big number.

\end{document}

The filename usually has the extension .Rnw, e.g., the above file is latex.Rnw. The idea is the same but the syntax for writing R code chunks and inline R expressions is different. An R code chunk starts with <<>>= (with optional chunk options inside the angle brackets) and ends with @. An inline R expression is written in \Sexpr{}.

The function knitr::knit() can compile an Rnw document to a LaTeX (.tex) output file, which can be further compiled to PDF through your LaTeX tools such as pdflatex. You can also use knitr::knit2pdf() to compile Rnw to PDF in one step. If you use RStudio, you can hit the Compile PDF button on the toolbar. Please note that the default method to compile Rnw documents is through Sweave, and you may want to change it to knitr (see the post http://stackoverflow.com/q/27592837/559676 for how to do that).

An Rnw document gives you the full power of LaTeX. This could be your last resort if there are typesetting problems that are really difficult to solve in Markdown. However, before you drop Markdown, we would like to remind you of the fact that a custom Pandoc LaTeX template may also be helpful (see Section 6.10).