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?



With Sweave really you need only two steps for a simple document as this my_sweave_file.Rnw:

Some text

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 knitr a simple compilation could de done with:

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

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

Another easy way is work with LyX instead of LaTeX directly, loading the knitr module, making automatically the "R Noweb" (.Rnw) to LaTeX exportation and all the compilation steps of the LaTeX file.

| improve this answer | |
  • 4
    You should really use a tool like latexmk or texi2pdf to run LaTeX (and, if necessary, BibTeX) as often as it needs to resolve all references. – krlmlr Sep 11 '13 at 7:21
  • @krlmlr, of course. Depending on what you have in LaTeX, you will need (or not) run pdflatex two or more times, may be also bibtex, or biber, or makeglosssaries, or makeindex, among others, manually, or with the help of tools as arara,rubber, your script, etc. But as OP is related with R and not the LateX features, my answer show the minimum working example. However, I will edit the answer to clarify the issue, thanks. – Fran Sep 11 '13 at 20:31
  • @Fran, thank you for your solution. I found that RStudio has a convenient editor to use with Knitr, as Yihui suggests. – ichbinallen Sep 11 '13 at 22:48
  • @AlPal, RStudio is what I use usually for .Rnw files, although with Sweave (it seem a little faster with complex files). – Fran Sep 11 '13 at 23:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.