[Tex/LaTex] How to build Knitr document from the command line

knitrrsweave

I would like to compile a knitr document from the command line. With Sweave, the sequence

R CMD Sweave my_sweave_file.Rnw
latex my_sweave_file.tex
latex my_sweave_file.tex
dvips my_sweave_file.dvi
ps2pdf my_sweave_file.ps

builds the final pdf file I want to publish. What is the corresponding build sequence with knitr?

Thanks!

Best Answer

With the command line with Sweave:

Really you need only two steps for a simple document as this my_sweave_file.Rnw:

\documentclass{article}
\begin{document}
Some text
<<RTest>>=
2+2
@
\end{document}

From the command line is enough:

R CMD Sweave my_sweave_file.Rnw
pdflatex my_sweave_file.tex

Or even only one:

R CMD Sweave --pdf my_sweave_file.Rnw

In case that you have cross-references (\ref or \cite commands, table of contents, index, glossaries, etc.) this will not enough, so you must also compile the generated .tex file with the appropriate tools and rerun pdlatex as needed. See Tools for automating document compilation if you have some problem with the compilation sequences.

With the command line with knitr:

A compilation of a simple document could be done with:

Rscript -e "library(knitr); knit('my_sweave_file.Rnw')"
pdflatex my_sweave_file.tex

Obviously, in complex Latex documents, you will need to add some compilation steps as above.

Without the command line

For the sake of completeness, an easy way to compile LateX+R documents is to work with LyX instead of LaTeX directly, loading the Sweave or Rnw(knitr) modules, making automatically in both case the "R Noweb" (.Rnw) to LaTeX exportation, and all the compilation steps of the LaTeX file.

Another possibility is use Rstudio to edit the .Rnw file and just push the PDF icon with the "Compile PDF" label. It is worth mention that you use also here Rmarkdown files (.Rmd extension) that offer the simplified syntax of markdown for text but can be converted as well to a LaTeX PDF. In this in case the compilation icon in changed by a is done by a dropdown menu "Knit" where you can select "Knit to PDF", with an obvious meaning.

Warning: The MWE without R chunk options options can be compiled equally with Sweave and knit functions, but there are chunk options specific for each of these functions: Some options cannot be used with knitr and many knitr options cannot be used with the older Sweave, so actually is preferable use knitr.