Debian Codegraph @

inst/examples/knitr-manual.Rnw

raw
1 %% LyX 2.2.1 created this file. For more info, see http://www.lyx.org/.
2 %% Do not edit unless you really know what you are doing.
3 \documentclass{article}
4 \usepackage[sc]{mathpazo}
5 \renewcommand{\sfdefault}{lmss}
6 \renewcommand{\ttdefault}{lmtt}
7 \usepackage[T1]{fontenc}
8 \usepackage{geometry}
9 \geometry{verbose,tmargin=2.5cm,bmargin=2.5cm,lmargin=2.5cm,rmargin=2.5cm}
10 \setcounter{secnumdepth}{2}
11 \setcounter{tocdepth}{2}
12 \usepackage{url}
13 \usepackage[authoryear]{natbib}
14 \usepackage[unicode=true,pdfusetitle,
15 bookmarks=true,bookmarksnumbered=true,bookmarksopen=true,bookmarksopenlevel=2,
16 breaklinks=false,pdfborder={0 0 1},backref=false,colorlinks=false]
17 {hyperref}
18 \hypersetup{
19 pdfstartview={XYZ null null 1}}
20 \usepackage{breakurl}
21
22 \makeatletter
23
24 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LyX specific LaTeX commands.
25 \providecommand{\LyX}{\texorpdfstring%
26 {L\kern-.1667em\lower.25em\hbox{Y}\kern-.125emX\@}
27 {LyX}}
28
29 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% User specified LaTeX commands.
30 \renewcommand{\textfraction}{0.05}
31 \renewcommand{\topfraction}{0.8}
32 \renewcommand{\bottomfraction}{0.8}
33 \renewcommand{\floatpagefraction}{0.75}
34
35 \usepackage[buttonsize=1em]{animate}
36
37 \makeatother
38
39 \begin{document}
40 <<setup, include=FALSE, cache=FALSE>>=
41 library(knitr)
42 ## set global chunk options
43 opts_chunk$set(fig.path='figure/manual-', cache.path='cache/manual-', fig.align='center', fig.show='hold', par=TRUE)
44 ## I use = but I can replace it with <-; set code/output width to be 68
45 options(formatR.arrow=TRUE, width=68, digits=4)
46 ## tune details of base graphics (https://yihui.org/knitr/hooks/)
47 knit_hooks$set(par=function(before, options, envir){
48 if (before && options$fig.show!='none') par(mar=c(4,4,.1,.1),cex.lab=.95,cex.axis=.9,mgp=c(2,.7,0),tcl=-.3)
49 })
50 @
51
52 \title{knitr: A General-Purpose Tool for Dynamic Report Generation in R}
53
54 \author{Yihui Xie}
55
56 \maketitle
57 The original paradigm of literate programming was brought forward
58 mainly for software development, or specifically, to mix source code
59 (for computer) and documentation (for human) together. Early systems
60 include \href{http://www.literateprogramming.com/web.pdf}{WEB} and
61 \href{http://www.cs.tufts.edu/~nr/noweb/}{Noweb}; Sweave \citep{leisch2002}
62 was derived from the latter, but it is less focused on documenting
63 software, instead it is mainly used for reproducible data analysis
64 and generating statistical reports. The \textbf{knitr} package \citep{R-knitr}
65 is following the steps of Sweave. For this manual, I assume readers
66 have some background knowledge of Sweave to understand the technical
67 details; for a reference of available options, hooks and demos, see
68 the package homepage \url{https://yihui.org/knitr/}.
69
70 \section{Hello World}
71
72 A natural question is why to reinvent the wheel. The short answer
73 is that extending Sweave by hacking \textsf{SweaveDrivers.R} in the
74 \textbf{utils} package is a difficult job to me. Many features in
75 \textbf{knitr} come naturally as users would have expected. Figure
76 \ref{fig:cars-demo} is a simple demo of some features of \textbf{knitr}.
77
78 \begin{figure}
79 <<cars-demo,dev='tikz',fig.width=4,fig.height=2.8,out.width='.45\\textwidth',message=FALSE,cache=TRUE>>=
80 fit=lm(dist~speed,data=cars) # linear regression
81 par(mar=c(4, 4, 1, .1), mgp=c(2,1,0))
82 with(cars,plot(speed,dist,panel.last=abline(fit)))
83 text(10,100,'$Y = \\beta_0 + \\beta_1x + \\epsilon$')
84 library(ggplot2)
85 qplot(speed, dist, data=cars)+geom_smooth()
86 @
87
88 \caption{\label{fig:cars-demo}A simple demo of possible output in \textbf{knitr}:
89 (1) multiple plots per chunk; (2) no need to \emph{print()} objects
90 in \textbf{ggplot2}; (3) device size is $4\times2.8$ (inches) but
91 output size is adjusted to \texttt{.45\textbackslash{}textwidth} in
92 chunk options; (4) base graphics and \textbf{ggplot2} can sit side
93 by side; (5) use the \emph{tikz()} device in \textbf{tikzDevice} by
94 setting chunk option \texttt{dev='tikz'} (hence can write native \protect\LaTeX{}
95 expressions in R plots); (6) code highlighting.}
96 \end{figure}
97
98 I would have chosen to hide the R code if this were a real report,
99 but here I show the code just for the sake of demonstration. If we
100 type \emph{qplot()} in R, we get a plot, and the same thing happens
101 in \textbf{knitr}. If we draw two plots in the code, \textbf{knitr}
102 will show two plots and we do not need to tell it how many plots are
103 there in the code in advance. If we set \texttt{out.width='.49\textbackslash{}\textbackslash{}textwidth'}
104 in chunk options, we get it in the final output document. If we say
105 \texttt{fig.align='center'}, the plots are centered. That's it. Many
106 enhancements and new features will be introduced later. If you come
107 from the Sweave land, you can take a look at the page of transition
108 first: \url{https://yihui.org/knitr/demo/sweave/}.
109
110 \section{Design}
111
112 The flow of processing an input file is similar to Sweave, and two
113 major differences are that \textbf{knitr} provides more flexibility
114 to the users to customize the processing, and has many built-in options
115 such as the support to a wide range of graphics devices and cache.
116 Below is a brief description of the process:
117 \begin{enumerate}
118 \item \textbf{knitr} takes an input file and automatically determines an
119 appropriate set of \href{https://yihui.org/knitr/patterns/}{patterns}
120 to use if they are not provided in advance (e.g. \textsf{file.Rnw}
121 will use \texttt{knit\_patterns\$get('rnw')});
122 \item a set of output \href{https://yihui.org/knitr/hooks/}{hooks} will
123 also be set up automatically according to the filename extension (e.g.
124 use \LaTeX{} environments or HTML elements to wrap up R results);
125 \item the input file is read in and split into pieces consisting of R code
126 chunks and normal texts; the former will be executed one after the
127 other, and the latter may contain global chunk options or inline R
128 code;
129 \item for each chunk, the code is evaluated using the \textbf{evaluate}
130 package \citep{R-evaluate}, and the results may be filtered according
131 to chunk options (e.g. \texttt{echo=FALSE} will remove the R source
132 code)
133
134 \begin{enumerate}
135 \item if \texttt{cache=TRUE} for this chunk, \textbf{knitr} will first check
136 if there are previously cached results under the cache directory before
137 really evaluating the chunk; if cached results exist and this code
138 chunk has not been changed since last run (use MD5 sum to verify),
139 the cached results will be (lazy-) loaded, otherwise new cache will
140 be built; if a cached chunk depends on other chunks (see the \texttt{dependson}
141 \href{https://yihui.org/knitr/options/}{option}) and any one of these
142 chunks has changed, this chunk must be forcibly updated (old cache
143 will be purged)
144 \item there are six types of possible output from \textbf{evaluate}, and
145 their classes are \texttt{character} (normal text output), \texttt{source}
146 (source code), \texttt{warning}, \texttt{message}, \texttt{error}
147 and \texttt{recordedplot}; an internal S3 generic function \emph{wrap()}
148 is used to deal with different types of output, using output hooks
149 defined in the object \texttt{knit\_hooks}
150 \item note plots are recorded as R objects before they are really saved
151 to files, so graphics devices will not be opened unless plots have
152 really been produced in a chunk
153 \item a code chunk is evaluated in a separate empty environment with the
154 global environment as its parent, and all the objects in this environment
155 after the evaluation will be saved if \texttt{cache=TRUE}
156 \item chunk hooks can be run before and/or after a chunk
157 \end{enumerate}
158 \item for normal texts, \textbf{knitr} will find inline R code (e.g. in
159 \texttt{\textbackslash{}Sexpr\{\}}) and evaluate it; the output is
160 wrapped by the \texttt{inline} hook;
161 \end{enumerate}
162 The hooks play important roles in \textbf{knitr}: this package makes
163 almost everything accessible to the users. Consider the following
164 extremely simple example which may demonstrate this freedom:
165
166 <<simple-example>>=
167 1+1
168 @
169
170 There are two parts in the final output: the source code \texttt{1
171 + 1} and the output \texttt{{[}1{]} 2}; the comment characters \texttt{\#\#}
172 are from the default chunk option \texttt{comment}. Users may define
173 a hook function for the source code like this to use the \texttt{lstlisting}
174 environment:
175
176 <<hook-source, eval=FALSE>>=
177 knit_hooks$set(source = function(x, options) {
178 paste('\\begin{lstlisting}\n', x, '\\end{lstlisting}\n', sep = '')
179 })
180 @
181
182 Similarly we can put other types of output into other environments.
183 There is no need to hack at \textsf{Sweave.sty} for \textbf{knitr}
184 and you can put the output in any environments. What is more, the
185 output hooks make \textbf{knitr} ready for other types of output,
186 and a typical one is HTML (there are built-in hooks). The website
187 has provided many examples demonstrating the flexibility of the output.
188
189 \section{Features}
190
191 The \textbf{knitr} package borrowed features such as tikz graphics
192 and cache from \textbf{pgfSweave} and \textbf{cacheSweave} respectively,
193 but the implementations are different. New features like code reference
194 from an external R script as well as output customization are also
195 introduced. The feature of hook functions in Sweave is re-implemented
196 and hooks have new usage now. There are several other small features
197 which are motivated from my everyday use of Sweave. For example, a
198 progress bar is provided when knitting a file so we roughly know how
199 long we still need to wait; output from inline R code (e.g. \texttt{\textbackslash{}Sexpr\{x{[}1{]}\}})
200 is automatically formatted in \TeX{} math notation (like \Sexpr{123456789})
201 if the result is numeric. You may check out a number of specific manuals
202 dedicated to specific features such as graphics in the website: \url{https://yihui.org/knitr/demo/}.
203
204 \subsection{Code Decoration}
205
206 The \textbf{highr} package \citep{R-highr} is used to highlight R
207 code, and the \textbf{formatR} package \citep{R-formatR} is used
208 to reformat R code (like \texttt{keep.source=FALSE} in Sweave but
209 will also try to retain comments). For \LaTeX{} output, the \textbf{framed}
210 package is used to decorate code chunks with a light gray background.
211 If this \LaTeX{} package is not found in the system, a version will
212 be copied directly from \textbf{knitr}. The prompt characters are
213 removed by default because they mangle the R source code in the output
214 and make it difficult to copy R code. The R output is masked in comments
215 by default based on the same rationale. It is easy to revert to the
216 output with prompts (set option \texttt{prompt=TRUE}), and you will
217 quickly realize the inconvenience to the readers if they want to copy
218 and run the code in the output document:
219
220 <<stupid-prompts, prompt=TRUE, comment=NA, highlight=FALSE>>=
221 x=rnorm(5)
222 x
223 var(x)
224 @
225
226 The example below shows the effect of \texttt{tidy=TRUE/FALSE}:
227
228 <<tidy-no, eval=FALSE, tidy=FALSE>>=
229 ## option tidy=FALSE
230 for(k in 1:10){j=cos(sin(k)*k^2)+3;print(j-5)}
231 @
232 <<tidy-yes, eval=FALSE, tidy=TRUE>>=
233 ## option tidy=TRUE
234 for(k in 1:10){j=cos(sin(k)*k^2)+3;print(j-5)}
235 @
236
237 Note \texttt{=} is replaced by \texttt{<-} because \texttt{options('formatR.arrow')}
238 was set to be \texttt{TRUE} in this document; see the documentation
239 of \emph{tidy.source()} in \textbf{formatR} for details.
240
241 Many highlighting themes can be used in \textbf{knitr}, which are
242 borrowed from the \textbf{highlight} package by \href{http://www.andre-simon.de/}{Andre Simon}\footnote{not the R package mentioned before; for a preview of these themes,
243 see \url{http://www.andre-simon.de/dokuwiki/doku.php?id=theme_examples}}; it is also possible to use themes from \url{http://www.eclipsecolorthemes.org/}
244 by providing a theme id to \textbf{knitr}\footnote{many thanks to \href{https://github.com/ramnathv}{Ramnath Vaidyanathan}
245 for the work on themes}. See \texttt{?knit\_theme} for details.
246
247 \subsection{Graphics}
248
249 Graphics is an important part of reports, and several enhancements
250 have been made in \textbf{knitr}. For example, grid graphics may not
251 need to be explicitly printed as long as the same code can produce
252 plots in R (in some cases, however, they have to be printed, e.g.
253 in a loop, because you have to do so in an R terminal).
254
255 \subsubsection{Graphical Devices}
256
257 Over a long time, a frequently requested feature for Sweave was the
258 support for other graphics devices, which has been implemented since
259 R 2.13.0. Instead of using logical options like \texttt{png} or \texttt{jpeg}
260 (this list can go on and on), \textbf{knitr} uses a single option
261 \texttt{dev} (like \texttt{grdevice} in Sweave) which has support
262 for more than 20 devices. For instance, \texttt{dev='png'} will use
263 the \emph{png()} device, and \texttt{dev='CairoJPEG'} uses the \emph{CairoJPEG()}
264 device in the \textbf{Cairo} package (it has to be installed first,
265 of course). If none of these devices is satisfactory, you can provide
266 the name of a customized device function, which must have been defined
267 before it is called.
268
269 \subsubsection{Plot Recording}
270
271 As mentioned before, all the plots in a code chunk are first recorded
272 as R objects and then ``replayed'' inside a graphical device to
273 generate plot files. The \textbf{evaluate} package will record plots
274 per \emph{expression} basis, in other words, the source code is split
275 into individual complete expressions and \textbf{evaluate} will examine
276 possible plot changes in snapshots after each single expression has
277 been evaluated. For example, the code below consists of three expressions,
278 out of which two are related to drawing plots, therefore \textbf{evaluate}
279 will produce two plots by default:
280
281 <<low-level-plots, fig.keep='all', dev='tikz', fig.width=2.5, fig.height=2.5, out.width='.3\\textwidth', cache=TRUE>>=
282 par(mar=c(3,3,.1,.1))
283 plot(1:10, ann=FALSE,las=1)
284 text(5,9,'mass $\\rightarrow$ energy\n$E=mc^2$')
285 @
286
287 This brings a significant difference with traditional tools in R for
288 dynamic report generation, since low-level plotting changes can also
289 be recorded. The option \texttt{fig.keep} controls which plots to
290 keep in the output; \texttt{fig.keep='all'} will keep low-level changes
291 as separate plots; by default (\texttt{fig.keep='high'}), \textbf{knitr}
292 will merge low-level plot changes into the previous high-level plot,
293 like most graphics devices do. This feature may be useful for teaching
294 R graphics step by step. Note, however, low-level plotting commands
295 in a single expression (a typical case is a loop) will not be recorded
296 accumulatively, but high-level plotting commands, regardless of where
297 they are, will always be recorded. For example, this chunk will only
298 produce 2 plots instead of 21 plots because there are 2 complete expressions:
299
300 <<low-plot-loop, eval=FALSE>>=
301 plot(0,0,type='n',ann=FALSE)
302 for(i in seq(0, 2*pi,length=20)) points(cos(i),sin(i))
303 @
304
305 But this will produce 20 plots as expected:
306
307 <<high-plot-loop, eval=FALSE>>=
308 for(i in seq(0, 2*pi,length=20)) {plot(cos(i),sin(i),xlim=c(-1,1),ylim=c(-1,1))}
309 @
310
311 As I showed in the beginning of this manual, it is straightforward
312 to let \textbf{knitr} keep all the plots in a chunk and insert them
313 into the output document, so we no longer need the \texttt{cat('\textbackslash{}\textbackslash{}includegraphics\{\}')}
314 trick.
315
316 We can discard all previous plots and keep the last one only by \texttt{fig.keep='last'},
317 or keep only the first plot by \texttt{fig.keep='first'}, or discard
318 all plots by \texttt{fig.keep='none'}.
319
320 \subsubsection{Plot Rearrangement}
321
322 The option \texttt{fig.show} can decide whether to hold all plots
323 while evaluating the code and ``flush'' all of them to the end of
324 a chunk (\texttt{fig.show='hold'}), or just insert them to the place
325 where they were created (by default \texttt{fig.show='asis'}). Here
326 is an example of \texttt{fig.show='asis'}:
327
328 <<fig-hold, fig.show='asis', dev='pdf', fig.width=6, fig.height=4, out.width='.35\\linewidth'>>=
329 contour(volcano) # contour lines
330 filled.contour(volcano) # fill contour plot with colors
331 @
332
333 Beside \texttt{hold} and \texttt{asis}, the option \texttt{fig.show}
334 can take a third value: \texttt{animate}, which makes it possible
335 to insert animations into the output document. In \LaTeX{}, the package
336 \textbf{animate} is used to put together image frames as an animation.
337 For animations to work, there must be more than one plot produced
338 in a chunk. The option \texttt{interval} controls the time interval
339 between animation frames; by default it is 1 second. Note you have
340 to add \texttt{\textbackslash{}usepackage\{animate\}} in the \LaTeX{}
341 preamble, because \textbf{knitr} will not add it automatically. Animations
342 in the PDF output can only be viewed in Adobe Reader.
343
344 As a simple demonstration, here is a \href{http://en.wikipedia.org/wiki/Mandelbrot_set}{Mandelbrot animation}
345 taken from the \textbf{animation} package \citep{R-animation}; note
346 the PNG device is used because PDF files are too large. You should
347 be able to see the animation immediately with Acrobat Reader since
348 it was set to play automatically:
349
350 <<animate-demo, fig.show='animate', dev='png', out.width='.45\\linewidth', interval=.5, aniopts='controls,loop,autoplay', cache=TRUE>>=
351 library(animation)
352 demo('Mandelbrot', echo = FALSE, package = 'animation')
353 @
354
355 \subsubsection{Plot Size}
356
357 The \texttt{fig.width} and \texttt{fig.height} options specify the
358 size of plots in the graphics device, and the real size in the output
359 document can be different (see \texttt{out.width} and \texttt{out.height}).
360 When there are multiple plots per chunk, it is possible to arrange
361 more than one plot per line in \LaTeX{} \textendash{} just specify
362 \texttt{out.width} to be less than half of the current line width,
363 e.g. \texttt{out.width='.49\textbackslash{}\textbackslash{}linewidth'}.
364
365 \subsubsection{The tikz Device}
366
367 Beside PDF, PNG and other traditional R graphical devices, \textbf{knitr}
368 has special support to tikz graphics via the \textbf{tikzDevice} package
369 \citep{R-tikzDevice}, which is similar to \textbf{pgfSweave}. If
370 we set the chunk option \texttt{dev='tikz'}, the \emph{tikz()} device
371 in \textbf{tikzDevice} will be used to save plots. Options \texttt{sanitize}
372 and \texttt{external} are related to the tikz device: see the documentation
373 of \emph{tikz()} for details. Note \texttt{external=TRUE} in \textbf{knitr}
374 has a different meaning with \textbf{pgfSweave} \textendash{} it means
375 \texttt{standAlone=TRUE} in \emph{tikz()}, and the tikz graphics output
376 will be compiled to PDF \emph{immediately} after it is created, so
377 the ``externalization'' does not depend on the \textbf{tikz} package;
378 to maintain consistency in (font) styles, \textbf{knitr} will read
379 the preamble of the input document and use it in the tikz device.
380 At the moment, I'm not sure if this is a faithful way to externalize
381 tikz graphics, but I have not seen any problems so far. The assumption
382 to make, however, is that you declare all the styles in the preamble;
383 \textbf{knitr} is agnostic of \emph{local} style changes in the body
384 of the document.
385
386 Below is an example taken from StackOverflow\footnote{\url{http://stackoverflow.com/q/8190087/559676}};
387 we usually have to write R code like this to obtain a math expression
388 $\mathrm{d}\mathbf{x}_{t}=\alpha[(\theta-\mathbf{x}_{t})\mathrm{d}t+4]\mathrm{d}B_{t}$
389 in R graphics:
390
391 <<math-expr-R, eval=FALSE>>=
392 qplot(1:10, 1:10) + opts(title = substitute(paste(d *
393 bolditalic(x)[italic(t)] == alpha * (theta - bolditalic(x)[italic(t)]) *
394 d * italic(t) + lambda * d * italic(B)[italic(t)]), list(lambda = 4)))
395 @
396
397 With the tikz device, it is both straightforward and more beautiful:
398
399 <<math-expr-tikz, dev='tikz', fig.width=5, fig.height=3, out.width='.55\\linewidth', cache=TRUE, message=FALSE>>=
400 library(ggplot2)
401 qplot(1:10, 1:10) +
402 labs(title = sprintf('$\\mathrm{d}\\mathbf{x}_{t} = \\alpha[(\\theta - \\mathbf{x}_{t})\\mathrm{d}t + %d]\\mathrm{d}B_{t}$', 4))
403 @
404
405 The advantage of tikz graphics is the consistency of styles\footnote{Users are encouraged to read the vignette of \textbf{tikzDevice},
406 which is the most beautiful vignette I have ever seen in R packages:
407 \url{http://cran.r-project.org/web/packages/tikzDevice/vignettes/tikzDevice.pdf}}, and one disadvantage is that \LaTeX{} may not be able to handle
408 too large tikz files (it can run out of memory). For example, an R
409 plot with tens of thousands of graphical elements may fail to compile
410 in \LaTeX{} if we use the tikz device. In such cases, we can switch
411 to the PDF or PNG device, or reconsider our decision on the type of
412 plots, e.g., a scatter plot with millions of points is usually difficult
413 to read, and a contour plot or a hexagon plot showing the 2D density
414 can be a better alternative (they are smaller in size).
415
416 The graphics manual contains more detailed information and you can
417 check it out in the \href{https://yihui.org/knitr/demo/graphics/}{website}.
418
419 \subsection{Cache}
420
421 The feature of cache is not a new idea \textendash{} both \textbf{cacheSweave}
422 and \textbf{weaver} have implemented it based on Sweave, with the
423 former using \textbf{filehash} and the latter using \textsf{.RData}
424 images; \textbf{cacheSweave} also supports lazy-loading of objects
425 based on \textbf{filehash}. The \textbf{knitr} package directly uses
426 internal base R functions to save (\emph{tools:::makeLazyLoadDB()})
427 and lazy-load objects (\emph{lazyLoad()}). These functions are either
428 undocumented or marked as internal, but as far as I understand, they
429 are the tools to implement lazy-loading for packages. The \textbf{cacheSweave}
430 vignette has clearly explained lazy-loading, and roughly speaking,
431 lazy-loading means an object will not be really loaded into memory
432 unless it is really used somewhere. This is very useful for cache;
433 sometimes we read a large object and cache it, then take a subset
434 for analysis and this subset is also cached; in the future, the initial
435 large object will not be loaded into R if our computation is only
436 based on the object of its subset.
437
438 The paths of cache files are determined by the chunk option \texttt{cache.path};
439 by default all cache files are created under a directory \textsf{cache}
440 relative to the current working directory, and if the option value
441 contains a directory (e.g. \texttt{cache.path='cache/abc-'}), cache
442 files will be stored under that directory (automatically created if
443 it does not exist). The cache is invalidated and purged on any changes
444 to the code chunk, including both the R code and chunk options\footnote{One exception is the \texttt{include} option, which is not cached
445 because \texttt{include=TRUE/FALSE} does not affect code evaluation;
446 meanwhile, the value \texttt{getOption('width')} is also cached, so
447 if you change this option, the cache will also be invalidated (this
448 option affects the width of text output)}; this means previous cache files of this chunk are removed (filenames
449 are identified by the chunk label). Unlike \textbf{pgfSweave}, cache
450 files will never accumulate since old cache files will always be removed
451 in \textbf{knitr}. Unlike \textbf{weaver} or \textbf{cacheSweave},
452 \textbf{knitr} will try to preserve these side-effects:
453 \begin{enumerate}
454 \item printed results: meaning that any output of a code chunk will be loaded
455 into the output document for a cached chunk, although it is not really
456 evaluated. The reason is \textbf{knitr} also cache the output of a
457 chunk as a character string. Note this means graphics output is also
458 cached since it is part of the output. It has been a pain for me for
459 a long time to have to lose output to gain cache;
460 \item loaded packages: after the evaluation of each cached chunk, the list
461 of packages used in the current R session is written to a file under
462 the cache path named \textsf{\_\_packages}; next time if a cached
463 chunk needs to be rebuilt, these packages will be loaded first. The
464 reasons for caching package names are, it can be slow to load some
465 packages, and a package might be loaded in a previous cached chunk
466 which is not available to the next cached chunk when only the latter
467 needs to be rebuilt. Note this only applies to cached chunks, and
468 for uncached chunks, you must always use \emph{library()} to load
469 packages explicitly;
470 \end{enumerate}
471 Although \textbf{knitr} tries to keep some side-effects, there are
472 still other types of side-effects like setting \emph{par()} or \emph{options()}
473 which are not cached. Users should be aware of these special cases,
474 and make sure to clearly separate the code which is not meant to be
475 cached to other chunks which are not cached, e.g., set all global
476 options in the first chunk of a document and do not cache that chunk.
477
478 Sometimes a cached chunk may need to use objects from other cached
479 chunks, which can bring a serious problem \textendash{} if objects
480 in previous chunks have changed, this chunk will not be aware of the
481 changes and will still use old cached results, unless there is a way
482 to detect such changes from other chunks. There is an option called
483 \texttt{dependson} in \textbf{cacheSweave} which does this job. We
484 can explicitly specify which other chunks this chunk depends on by
485 setting an option like \texttt{dependson='chunkA;chunkB'} or equivalently
486 \texttt{dependson=c('chunkA', 'chunkB')}. Each time the cache of a
487 chunk is rebuilt, all other chunks which depend on this chunk will
488 lose cache, hence their cache will be rebuilt as well.
489
490 Another way to specify the dependencies among chunks is to use the
491 chunk option \texttt{autodep} and the function \emph{dep\_auto()}.
492 This is an experimental feature borrowed from \textbf{weaver} which
493 frees us from setting chunk dependencies manually. The basic idea
494 is, if a latter chunk uses any objects created from a previous chunk,
495 the latter chunk is said to depend on the previous one. The function
496 \emph{find_globals()} in the \textbf{xfun} package is used to
497 find out all global objects in a chunk, and according to its documentation,
498 the result is an approximation. Global objects roughly mean the ones
499 which are not created locally, e.g. in the expression \texttt{function()
500 \{y <- x\}}, \texttt{x} should be a global object, whereas \texttt{y}
501 is local. Meanwhile, we also need to save the list of objects created
502 in each cached chunk, so that we can compare them to the global objects
503 in latter chunks. For example, if chunk A created an object \texttt{x}
504 and chunk B uses this object, chunk B must depend on A, i.e. whenever
505 A changes, B must also be updated. When \texttt{autodep=TRUE}, \textbf{knitr}
506 will write out the names of objects created in a cached chunk as well
507 as those global objects in two files named \textsf{\_\_objects} and
508 \textsf{\_\_globals} respectively; later we can use the function \emph{dep\_auto()}
509 to analyze the object names to figure out the dependencies automatically.
510 See \url{https://yihui.org/knitr/demo/cache/} for examples.
511
512 Yet another way to specify dependencies is \emph{dep\_prev()}: this
513 is a conservative approach which sets the dependencies so that a cached
514 chunk will depend on all its previous chunks, i.e. whenever a previous
515 chunk is updated, all later chunks will be updated accordingly.
516
517 \subsection{Code Externalization}
518
519 It can be more convenient to write R code in a separate file, rather
520 than mixing it into a \LaTeX{} document; for example, we can run
521 R code successively in a pure R script from one chunk to the other
522 without jumping through other texts. Since I prefer using \LyX{}
523 to write reports, Sweave is even more inconvenient because I have
524 to recompile the whole document each time, even if I only want to
525 know the results of a single chunk. Therefore \textbf{knitr} introduced
526 the feature of code externalization to a separate R script. Currently
527 the setting is like this: the R script also uses chunk labels (marked
528 in the form \texttt{\#\# -{}-{}-{}- chunk-label} by default); if the
529 code chunk in the input document is empty, \textbf{knitr} will match
530 its label with the label in the R script to input external R code.
531 For example, suppose this is a code chunk labelled as \texttt{Q1}
532 in an R script named \textsf{homework1-xie.R} which is under the same
533 directory as the Rnw document:
534
535 <<ext-r-code, eval=FALSE>>=
536 ## ---- Q1 ---------------------
537 gcd = function(m, n) {
538 while ((r <- m %% n) != 0) {
539 m = n; n = r
540 }
541 n
542 }
543 @
544
545 In the Rnw document, we can first read the script using the function
546 \emph{read\_chunk()}:
547
548 <<read-chunk, eval=FALSE>>=
549 read_chunk('homework1-xie.R')
550 @
551
552 This is usually done in an early chunk, and we can use the chunk \texttt{Q1}
553 later in the Rnw document:
554
555 <<use-ext-chunk, echo=FALSE, comment=NA>>=
556 cat('<<Q1, echo=TRUE, tidy=TRUE>>=','@',sep='\n')
557 @
558
559 Different documents can read the same R script, so the R code can
560 be reusable across different input documents.
561
562 \subsection{Evaluation of Chunk Options\label{subsec:conditional}}
563
564 By default \textbf{knitr} uses a new syntax to parse chunk options:
565 it treats them as function arguments instead of a text string to be
566 split to obtain option values. This gives the user much more power
567 than the old syntax; we can pass arbitrary R objects to chunk options
568 besides simple ones like \texttt{TRUE}/\texttt{FALSE}, numbers and
569 character strings. The page \url{https://yihui.org/knitr/demo/sweave/}
570 has given two examples to show the advantages of the new syntax. Here
571 we show yet another useful application.
572
573 Before \textbf{knitr} 0.3, there was a feature named ``conditional
574 evaluation''\footnote{request from \url{https://plus.google.com/u/0/116405544829727492615/posts/43WrRUffjzK}}.
575 The idea is, instead of setting chunk options \texttt{eval} and \texttt{echo}
576 to be \texttt{TRUE} or \texttt{FALSE} (constants), their values can
577 be controlled by global variables in the current R session. This enables
578 \textbf{knitr} to conditionally evaluate code chunks according to
579 variables. For example, here we assign \texttt{TRUE} to a variable
580 \texttt{dothis}:
581
582 <<cond-variable>>=
583 dothis=TRUE
584 @
585
586 In the next chunk, we set chunk options \texttt{eval=dothis} and \texttt{echo=!dothis},
587 both are valid R expressions since the variable \texttt{dothis} exists.
588 As we can see, the source code is hidden, but it was indeed evaluated:
589
590 <<cond-out1, eval=dothis, echo=!dothis>>=
591 print('you cannot see my source because !dothis is FALSE')
592 @
593
594 Then we set \texttt{eval=dothis} and \texttt{echo=dothis} for another
595 chunk:
596
597 <<cond-out2,eval=dothis,echo=dothis>>=
598 dothis
599 @
600
601 If we change the value of \texttt{dothis} to \texttt{FALSE}, neither
602 of the above chunks will be evaluated any more. Therefore we can control
603 many chunks with a single variable, and present results selectively.
604
605 This old feature requires \textbf{knitr} to treat \texttt{eval} and
606 \texttt{echo} specially, and we can easily see that it is no longer
607 necessary with the new syntax: \texttt{eval=dothis} will tell R to
608 find the variable \texttt{dothis} automatically just like we call
609 a function \texttt{foobar(eval = dothis)}. What is more, all options
610 will be evaluated as R expressions unless they are already constants
611 which do not need to be evaluated, so this old feature has been generalized
612 to all other options naturally.
613
614 \subsection{Customization}
615
616 The \textbf{knitr} package is ready for customization. Both the patterns
617 and hooks can be customized; see the package website for details.
618 Here I show an example on how to save \textbf{rgl} plots \citep{R-rgl}
619 using a customized hook function. First we define a hook named \texttt{rgl}
620 using the function \emph{hook\_rgl()} in \textbf{rgl}:
621
622 <<rgl-demo>>=
623 library(rgl)
624 knit_hooks$set(rgl = hook_rgl)
625 head(hook_rgl) # the hook function is defined as this
626 @
627
628 Then we only have to set the chunk option \texttt{rgl=TRUE}:
629
630 <<fancy-rgl, rgl=TRUE, dev='png', fig.width=5, fig.height=5, out.width='2in', message=FALSE, warning=FALSE, cache=TRUE>>=
631 library(rgl)
632 demo('bivar', package='rgl', echo=FALSE)
633 par3d(zoom=.7)
634 @
635
636 Due to the flexibility of output hooks, \textbf{knitr} supports several
637 different output formats. The implementation is fairly easy, e.g.,
638 for \LaTeX{} we put R output in \texttt{verbatim} environments, and
639 in HTML, it is only a matter of putting output in \texttt{div} layers.
640 These are simply character string operations. Many demos in \url{https://yihui.org/knitr/demo/}
641 show this idea clearly. This manual did not cover all the features
642 of \textbf{knitr}, and users are encouraged to thumb through the website
643 to know more possible features.
644
645 \section{Editors}
646
647 You can use any text editors to write the source documents, but some
648 have built-in support for \textbf{knitr}. Both RStudio (\url{http://www.rstudio.org})
649 and \LyX{} (\url{http://www.lyx.org}) have full support for \textbf{knitr},
650 and you can compile the document to PDF with just one click. See \url{https://yihui.org/knitr/demo/rstudio/}
651 and \url{https://yihui.org/knitr/demo/lyx/} respectively. It is also
652 possible to support other editors like \href{https://yihui.org/knitr/demo/eclipse/}{Eclipse},
653 \href{https://yihui.org/knitr/demo/editors/}{Texmaker and WinEdt};
654 see the demo list in the website for configuration instructions.
655
656 \section*{About This Document}
657
658 This manual was written in \LyX{} and compiled with \textbf{knitr}
659 (version \Sexpr{packageVersion('knitr')}). The \LyX{} source and
660 the Rnw document exported from \LyX{} can be found under these directories:
661
662 <<source-location, eval=FALSE>>=
663 system.file('examples', 'knitr-manual.lyx', package='knitr') # lyx source
664 system.file('examples', 'knitr-manual.Rnw', package='knitr') # Rnw source
665 @
666
667 You can use the function \emph{knit()} to knit the Rnw document (remember
668 to put the two \textsf{.bib} files under the same directory), and
669 you need to make sure all the R packages used in this document are
670 installed:
671
672 <<required-packages, eval=FALSE>>=
673 install.packages(c('animation', 'rgl', 'tikzDevice', 'ggplot2'))
674 @
675
676 Feedback and comments on this manual and the package are always welcome.
677 Bug reports and feature requests can be sent to \url{https://github.com/yihui/knitr/issues},
678 and questions can be delivered to the \href{mailto:[email protected]}{mailing list}
679 \url{https://groups.google.com/group/knitr}.
680
681 % when knitr is updated, this chunk will be updated; why?
682 <<auto-bib, version=packageVersion('knitr'), echo=FALSE, cache=TRUE, message=FALSE, warning=FALSE>>=
683 # write all packages in the current session to a bib file
684 write_bib(c(.packages(), 'evaluate', 'formatR', 'highr'), file = 'knitr-packages.bib')
685 @
686
687 \bibliographystyle{jss}
688 \bibliography{knitr-manual,knitr-packages}
689
690 \end{document}