Knitr from Sweave
If you have experience using Sweave with LaTeX, you’ll find that it will be an easy transition from Sweave to knitr, and one well worth making. A number of Sweave annoyances have been eliminated, but I think the big feature is that for less formal reports you can use knitr with R Markdown or with AsciiDoc, which are a lot easier to write than LaTeX, and you don’t have to deal with page breaks in the resulting web page.
Yihui Xie has written a great document on the Transition from Sweave to knitr. Here, I’ll just give a thumbnail sketch.
Chunks are still delimited with <<>>=
and @
, and in-line code
still uses \Sexpr{ }
.
Here are some of the new things in knitr:
-
A number of chunk options have been changed, and for good reason: In knitr, all of the chunk options are valid R code. So, for example, you use
results="hide"
rather thanresults=hide
.Because of the change in chunk options, the knitr package includes a function,
Sweave2knitr()
for converting old Sweave-based.Rnw
files to the knitr syntax. -
The chunk options
width
andheight
were changed tofig.width
andfig.height
, respectively. Again, see Yihui’s page on Transition from Sweave to knitr. -
Chunk names/labels must be distinct. In Sweave, I’d often have the problem of copy-pasting one chunk to create another, particularly for figures. If (or really when) I forgot to change the chunk label, the second chunk’s figure would overwrite the first chunk’s figure, and you’d just get that second figure in duplicate in the two places. In knitr, if two chunks have the same label, knitr halts with an error. This is a good thing!
-
You don’t have to indicate that a chunk is going to produce a figure (the old
fig=TRUE
). If the chunk produces a figure, knitr will include the figure. -
A chunk can produce more than one figure. Multiple image files will be created, and they’ll be inserted into the final document one after the other.
-
You don’t have to worry about that
Sweave.sty
file. The knitr package takes care of this sort of thing. -
To process the code chunks and convert the
.Rnw
file to.tex
, you use theknit()
function in the knitr package rather thanSweave()
.R -e 'library(knitr);knit("my_file.Rnw")'