Debian Codegraph @

inst/examples/knitr-manual.lyx

raw
1 #LyX 2.1 created this file. For more info see http://www.lyx.org/
2 \lyxformat 474
3 \begin_document
4 \begin_header
5 \textclass article
6 \begin_preamble
7 \renewcommand{\textfraction}{0.05}
8 \renewcommand{\topfraction}{0.8}
9 \renewcommand{\bottomfraction}{0.8}
10 \renewcommand{\floatpagefraction}{0.75}
11
12 \usepackage[buttonsize=1em]{animate}
13 \end_preamble
14 \use_default_options true
15 \begin_modules
16 knitr
17 \end_modules
18 \maintain_unincluded_children false
19 \language english
20 \language_package none
21 \inputencoding default
22 \fontencoding global
23 \font_roman palatino
24 \font_sans lmss
25 \font_typewriter lmtt
26 \font_math auto
27 \font_default_family default
28 \use_non_tex_fonts false
29 \font_sc true
30 \font_osf false
31 \font_sf_scale 100
32 \font_tt_scale 100
33 \graphics default
34 \default_output_format default
35 \output_sync 0
36 \bibtex_command default
37 \index_command default
38 \paperfontsize default
39 \spacing single
40 \use_hyperref true
41 \pdf_bookmarks true
42 \pdf_bookmarksnumbered true
43 \pdf_bookmarksopen true
44 \pdf_bookmarksopenlevel 2
45 \pdf_breaklinks false
46 \pdf_pdfborder false
47 \pdf_colorlinks false
48 \pdf_backref false
49 \pdf_pdfusetitle true
50 \pdf_quoted_options "pdfstartview={XYZ null null 1}"
51 \papersize default
52 \use_geometry true
53 \use_package amsmath 1
54 \use_package amssymb 1
55 \use_package cancel 1
56 \use_package esint 1
57 \use_package mathdots 1
58 \use_package mathtools 1
59 \use_package mhchem 1
60 \use_package stackrel 1
61 \use_package stmaryrd 1
62 \use_package undertilde 1
63 \cite_engine natbib
64 \cite_engine_type authoryear
65 \biblio_style plainnat
66 \use_bibtopic false
67 \use_indices false
68 \paperorientation portrait
69 \suppress_date false
70 \justification true
71 \use_refstyle 1
72 \index Index
73 \shortcut idx
74 \color #008000
75 \end_index
76 \leftmargin 2.5cm
77 \topmargin 2.5cm
78 \rightmargin 2.5cm
79 \bottommargin 2.5cm
80 \secnumdepth 2
81 \tocdepth 2
82 \paragraph_separation indent
83 \paragraph_indentation default
84 \quotes_language english
85 \papercolumns 1
86 \papersides 1
87 \paperpagestyle default
88 \tracking_changes false
89 \output_changes false
90 \html_math_output 0
91 \html_css_as_file 0
92 \html_be_strict false
93 \end_header
94
95 \begin_body
96
97 \begin_layout Standard
98 \begin_inset ERT
99 status open
100
101 \begin_layout Plain Layout
102
103 <<setup, include=FALSE, cache=FALSE>>=
104 \end_layout
105
106 \begin_layout Plain Layout
107
108 library(knitr)
109 \end_layout
110
111 \begin_layout Plain Layout
112
113 ## set global chunk options
114 \end_layout
115
116 \begin_layout Plain Layout
117
118 opts_chunk$set(fig.path='figure/manual-', cache.path='cache/manual-', fig.align='ce
119 nter', fig.show='hold', par=TRUE)
120 \end_layout
121
122 \begin_layout Plain Layout
123
124 ## I use = but I can replace it with <-; set code/output width to be 68
125 \end_layout
126
127 \begin_layout Plain Layout
128
129 options(formatR.arrow=TRUE, width=68, digits=4)
130 \end_layout
131
132 \begin_layout Plain Layout
133
134 ## tune details of base graphics (https://yihui.org/knitr/hooks)
135 \end_layout
136
137 \begin_layout Plain Layout
138
139 knit_hooks$set(par=function(before, options, envir){
140 \end_layout
141
142 \begin_layout Plain Layout
143
144 if (before && options$fig.show!='none') par(mar=c(4,4,.1,.1),cex.lab=.95,cex.axis=.9,mg
145 p=c(2,.7,0),tcl=-.3)
146 \end_layout
147
148 \begin_layout Plain Layout
149
150 })
151 \end_layout
152
153 \begin_layout Plain Layout
154
155 @
156 \end_layout
157
158 \end_inset
159
160
161 \end_layout
162
163 \begin_layout Title
164 knitr: A General-Purpose Tool for Dynamic Report Generation in R
165 \end_layout
166
167 \begin_layout Author
168 Yihui Xie
169 \end_layout
170
171 \begin_layout Standard
172 The original paradigm of literate programming was brought forward mainly
173 for software development, or specifically, to mix source code (for computer)
174 and documentation (for human) together.
175 Early systems include
176 \begin_inset CommandInset href
177 LatexCommand href
178 name "WEB"
179 target "http://www.literateprogramming.com/web.pdf"
180
181 \end_inset
182
183 and
184 \begin_inset CommandInset href
185 LatexCommand href
186 name "Noweb"
187 target "http://www.cs.tufts.edu/~nr/noweb/"
188
189 \end_inset
190
191 ; Sweave
192 \begin_inset CommandInset citation
193 LatexCommand citep
194 key "leisch2002"
195
196 \end_inset
197
198 was derived from the latter, but it is less focused on documenting software,
199 instead it is mainly used for reproducible data analysis and generating
200 statistical reports.
201 The
202 \series bold
203 knitr
204 \series default
205 package
206 \begin_inset CommandInset citation
207 LatexCommand citep
208 key "R-knitr"
209
210 \end_inset
211
212 is following the steps of Sweave.
213 For this manual, I assume readers have some background knowledge of Sweave
214 to understand the technical details; for a reference of available options,
215 hooks and demos, see the package homepage
216 \begin_inset Flex URL
217 status collapsed
218
219 \begin_layout Plain Layout
220
221 https://yihui.org/knitr/
222 \end_layout
223
224 \end_inset
225
226 .
227 \end_layout
228
229 \begin_layout Section
230 Hello World
231 \end_layout
232
233 \begin_layout Standard
234 A natural question is why to reinvent the wheel.
235 The short answer is that extending Sweave by hacking
236 \family sans
237 SweaveDrivers.R
238 \family default
239 in the
240 \series bold
241 utils
242 \series default
243 package is a difficult job to me.
244 Many features in
245 \series bold
246 knitr
247 \series default
248 come naturally as users would have expected.
249 Figure
250 \begin_inset CommandInset ref
251 LatexCommand ref
252 reference "fig:cars-demo"
253
254 \end_inset
255
256 is a simple demo of some features of
257 \series bold
258 knitr
259 \series default
260 .
261 \end_layout
262
263 \begin_layout Standard
264 \begin_inset Float figure
265 wide false
266 sideways false
267 status open
268
269 \begin_layout Plain Layout
270 \begin_inset ERT
271 status open
272
273 \begin_layout Plain Layout
274
275 <<cars-demo,dev='tikz',fig.width=4,fig.height=2.8,out.width='.45
276 \backslash
277
278 \backslash
279 textwidth',message=FALSE,cache=TRUE>>=
280 \end_layout
281
282 \begin_layout Plain Layout
283
284 fit=lm(dist~speed,data=cars) # linear regression
285 \end_layout
286
287 \begin_layout Plain Layout
288
289 par(mar=c(4, 4, 1, .1), mgp=c(2,1,0))
290 \end_layout
291
292 \begin_layout Plain Layout
293
294 with(cars,plot(speed,dist,panel.last=abline(fit)))
295 \end_layout
296
297 \begin_layout Plain Layout
298
299 text(10,100,'$Y =
300 \backslash
301
302 \backslash
303 beta_0 +
304 \backslash
305
306 \backslash
307 beta_1x +
308 \backslash
309
310 \backslash
311 epsilon$')
312 \end_layout
313
314 \begin_layout Plain Layout
315
316 library(ggplot2)
317 \end_layout
318
319 \begin_layout Plain Layout
320
321 qplot(speed, dist, data=cars)+geom_smooth()
322 \end_layout
323
324 \begin_layout Plain Layout
325
326 @
327 \end_layout
328
329 \end_inset
330
331
332 \end_layout
333
334 \begin_layout Plain Layout
335 \begin_inset Caption Standard
336
337 \begin_layout Plain Layout
338 \begin_inset CommandInset label
339 LatexCommand label
340 name "fig:cars-demo"
341
342 \end_inset
343
344 A simple demo of possible output in
345 \series bold
346 knitr
347 \series default
348 : (1) multiple plots per chunk; (2) no need to
349 \emph on
350 print()
351 \emph default
352 objects in
353 \series bold
354 ggplot2
355 \series default
356 ; (3) device size is
357 \begin_inset Formula $4\times2.8$
358 \end_inset
359
360 (inches) but output size is adjusted to
361 \family typewriter
362 .45
363 \backslash
364 textwidth
365 \family default
366 in chunk options; (4) base graphics and
367 \series bold
368 ggplot2
369 \series default
370 can sit side by side; (5) use the
371 \emph on
372 tikz()
373 \emph default
374 device in
375 \series bold
376 tikzDevice
377 \series default
378 by setting chunk option
379 \family typewriter
380 dev='tikz'
381 \family default
382 (hence can write native LaTeX expressions in R plots); (6) code highlighting.
383 \end_layout
384
385 \end_inset
386
387
388 \end_layout
389
390 \end_inset
391
392
393 \end_layout
394
395 \begin_layout Standard
396 I would have chosen to hide the R code if this were a real report, but here
397 I show the code just for the sake of demonstration.
398 If we type
399 \emph on
400 qplot()
401 \emph default
402 in R, we get a plot, and the same thing happens in
403 \series bold
404 knitr
405 \series default
406 .
407 If we draw two plots in the code,
408 \series bold
409 knitr
410 \series default
411 will show two plots and we do not need to tell it how many plots are there
412 in the code in advance.
413 If we set
414 \family typewriter
415 out.width='.49
416 \backslash
417
418 \backslash
419 textwidth'
420 \family default
421 in chunk options, we get it in the final output document.
422 If we say
423 \family typewriter
424 fig.align='center'
425 \family default
426 , the plots are centered.
427 That's it.
428 Many enhancements and new features will be introduced later.
429 If you come from the Sweave land, you can take a look at the page of transition
430 first:
431 \begin_inset Flex URL
432 status collapsed
433
434 \begin_layout Plain Layout
435
436 https://yihui.org/knitr/demo/sweave/
437 \end_layout
438
439 \end_inset
440
441 .
442 \end_layout
443
444 \begin_layout Section
445 Design
446 \end_layout
447
448 \begin_layout Standard
449 The flow of processing an input file is similar to Sweave, and two major
450 differences are that
451 \series bold
452 knitr
453 \series default
454 provides more flexibility to the users to customize the processing, and
455 has many built-in options such as the support to a wide range of graphics
456 devices and cache.
457 Below is a brief description of the process:
458 \end_layout
459
460 \begin_layout Enumerate
461
462 \series bold
463 knitr
464 \series default
465 takes an input file and automatically determines an appropriate set of
466
467 \begin_inset CommandInset href
468 LatexCommand href
469 name "patterns"
470 target "https://yihui.org/knitr/patterns/"
471
472 \end_inset
473
474 to use if they are not provided in advance (e.g.
475
476 \family sans
477 file.Rnw
478 \family default
479 will use
480 \family typewriter
481 knit_patterns$get('rnw')
482 \family default
483 );
484 \end_layout
485
486 \begin_layout Enumerate
487 a set of output
488 \begin_inset CommandInset href
489 LatexCommand href
490 name "hooks"
491 target "https://yihui.org/knitr/hooks/"
492
493 \end_inset
494
495 will also be set up automatically according to the filename extension (e.g.
496 use LaTeX environments or HTML elements to wrap up R results);
497 \end_layout
498
499 \begin_layout Enumerate
500 the input file is read in and split into pieces consisting of R code chunks
501 and normal texts; the former will be executed one after the other, and
502 the latter may contain global chunk options or inline R code;
503 \end_layout
504
505 \begin_layout Enumerate
506 for each chunk, the code is evaluated using the
507 \series bold
508 evaluate
509 \series default
510 package
511 \begin_inset CommandInset citation
512 LatexCommand citep
513 key "R-evaluate"
514
515 \end_inset
516
517 , and the results may be filtered according to chunk options (e.g.
518
519 \family typewriter
520 echo=FALSE
521 \family default
522 will remove the R source code)
523 \end_layout
524
525 \begin_deeper
526 \begin_layout Enumerate
527 if
528 \family typewriter
529 cache=TRUE
530 \family default
531 for this chunk,
532 \series bold
533 knitr
534 \series default
535 will first check if there are previously cached results under the cache
536 directory before really evaluating the chunk; if cached results exist and
537 this code chunk has not been changed since last run (use MD5 sum to verify),
538 the cached results will be (lazy-) loaded, otherwise new cache will be
539 built; if a cached chunk depends on other chunks (see the
540 \family typewriter
541 dependson
542 \family default
543
544 \begin_inset CommandInset href
545 LatexCommand href
546 name "option"
547 target "https://yihui.org/knitr/options/"
548
549 \end_inset
550
551 ) and any one of these chunks has changed, this chunk must be forcibly updated
552 (old cache will be purged)
553 \end_layout
554
555 \begin_layout Enumerate
556 there are six types of possible output from
557 \series bold
558 evaluate
559 \series default
560 , and their classes are
561 \family typewriter
562 character
563 \family default
564 (normal text output),
565 \family typewriter
566 source
567 \family default
568 (source code),
569 \family typewriter
570 warning
571 \family default
572 ,
573 \family typewriter
574 message
575 \family default
576 ,
577 \family typewriter
578 error
579 \family default
580 and
581 \family typewriter
582 recordedplot
583 \family default
584 ; an internal S3 generic function
585 \emph on
586 wrap()
587 \emph default
588 is used to deal with different types of output, using output hooks defined
589 in the object
590 \family typewriter
591 knit_hooks
592 \end_layout
593
594 \begin_layout Enumerate
595 note plots are recorded as R objects before they are really saved to files,
596 so graphics devices will not be opened unless plots have really been produced
597 in a chunk
598 \end_layout
599
600 \begin_layout Enumerate
601 a code chunk is evaluated in a separate empty environment with the global
602 environment as its parent, and all the objects in this environment after
603 the evaluation will be saved if
604 \family typewriter
605 cache=TRUE
606 \end_layout
607
608 \begin_layout Enumerate
609 chunk hooks can be run before and/or after a chunk
610 \end_layout
611
612 \end_deeper
613 \begin_layout Enumerate
614 for normal texts,
615 \series bold
616 knitr
617 \series default
618 will find inline R code (e.g.
619 in
620 \family typewriter
621
622 \backslash
623 Sexpr{}
624 \family default
625 ) and evaluate it; the output is wrapped by the
626 \family typewriter
627 inline
628 \family default
629 hook;
630 \end_layout
631
632 \begin_layout Standard
633 The hooks play important roles in
634 \series bold
635 knitr
636 \series default
637 : this package makes almost everything accessible to the users.
638 Consider the following extremely simple example which may demonstrate this
639 freedom:
640 \end_layout
641
642 \begin_layout Standard
643 \begin_inset ERT
644 status open
645
646 \begin_layout Plain Layout
647
648 <<simple-example>>=
649 \end_layout
650
651 \begin_layout Plain Layout
652
653 1+1
654 \end_layout
655
656 \begin_layout Plain Layout
657
658 @
659 \end_layout
660
661 \end_inset
662
663
664 \end_layout
665
666 \begin_layout Standard
667 There are two parts in the final output: the source code
668 \family typewriter
669 1 + 1
670 \family default
671 and the output
672 \family typewriter
673 [1] 2
674 \family default
675 ; the comment characters
676 \family typewriter
677 ##
678 \family default
679 are from the default chunk option
680 \family typewriter
681 comment
682 \family default
683 .
684 Users may define a hook function for the source code like this to use the
685
686 \family typewriter
687 lstlisting
688 \family default
689 environment:
690 \end_layout
691
692 \begin_layout Standard
693 \begin_inset ERT
694 status open
695
696 \begin_layout Plain Layout
697
698 <<hook-source, eval=FALSE>>=
699 \end_layout
700
701 \begin_layout Plain Layout
702
703 knit_hooks$set(source = function(x, options) {
704 \end_layout
705
706 \begin_layout Plain Layout
707
708 paste('
709 \backslash
710
711 \backslash
712 begin{lstlisting}
713 \backslash
714 n', x, '
715 \backslash
716
717 \backslash
718 end{lstlisting}
719 \backslash
720 n', sep = '')
721 \end_layout
722
723 \begin_layout Plain Layout
724
725 })
726 \end_layout
727
728 \begin_layout Plain Layout
729
730 @
731 \end_layout
732
733 \end_inset
734
735
736 \end_layout
737
738 \begin_layout Standard
739 Similarly we can put other types of output into other environments.
740 There is no need to hack at
741 \family sans
742 Sweave.sty
743 \family default
744 for
745 \series bold
746 knitr
747 \series default
748 and you can put the output in any environments.
749 What is more, the output hooks make
750 \series bold
751 knitr
752 \series default
753 ready for other types of output, and a typical one is HTML (there are built-in
754 hooks).
755 The website has provided many examples demonstrating the flexibility of
756 the output.
757 \end_layout
758
759 \begin_layout Section
760 Features
761 \end_layout
762
763 \begin_layout Standard
764 The
765 \series bold
766 knitr
767 \series default
768 package borrowed features such as tikz graphics and cache from
769 \series bold
770 pgfSweave
771 \series default
772 and
773 \series bold
774 cacheSweave
775 \series default
776 respectively, but the implementations are different.
777 New features like code reference from an external R script as well as output
778 customization are also introduced.
779 The feature of hook functions in Sweave is re-implemented and hooks have
780 new usage now.
781 There are several other small features which are motivated from my everyday
782 use of Sweave.
783 For example, a progress bar is provided when knitting a file so we roughly
784 know how long we still need to wait; output from inline R code (e.g.
785
786 \family typewriter
787
788 \backslash
789 Sexpr{x[1]}
790 \family default
791 ) is automatically formatted in TeX math notation (like
792 \begin_inset ERT
793 status collapsed
794
795 \begin_layout Plain Layout
796
797
798 \backslash
799 Sexpr{123456789}
800 \end_layout
801
802 \end_inset
803
804 ) if the result is numeric.
805 You may check out a number of specific manuals dedicated to specific features
806 such as graphics in the website:
807 \begin_inset Flex URL
808 status collapsed
809
810 \begin_layout Plain Layout
811
812 https://yihui.org/knitr/demo/
813 \end_layout
814
815 \end_inset
816
817 .
818 \end_layout
819
820 \begin_layout Subsection
821 Code Decoration
822 \end_layout
823
824 \begin_layout Standard
825 The
826 \series bold
827 highr
828 \series default
829 package
830 \begin_inset CommandInset citation
831 LatexCommand citep
832 key "R-highr"
833
834 \end_inset
835
836 is used to highlight R code, and the
837 \series bold
838 formatR
839 \series default
840 package
841 \begin_inset CommandInset citation
842 LatexCommand citep
843 key "R-formatR"
844
845 \end_inset
846
847 is used to reformat R code (like
848 \family typewriter
849 keep.source=FALSE
850 \family default
851 in Sweave but will also try to retain comments).
852 For LaTeX output, the
853 \series bold
854 framed
855 \series default
856 package is used to decorate code chunks with a light gray background.
857 If this LaTeX package is not found in the system, a version will be copied
858 directly from
859 \series bold
860 knitr
861 \series default
862 .
863 The prompt characters are removed by default because they mangle the R
864 source code in the output and make it difficult to copy R code.
865 The R output is masked in comments by default based on the same rationale.
866 It is easy to revert to the output with prompts (set option
867 \family typewriter
868 prompt=TRUE
869 \family default
870 ), and you will quickly realize the inconvenience to the readers if they
871 want to copy and run the code in the output document:
872 \end_layout
873
874 \begin_layout Standard
875 \begin_inset ERT
876 status open
877
878 \begin_layout Plain Layout
879
880 <<stupid-prompts, prompt=TRUE, comment=NA, highlight=FALSE>>=
881 \end_layout
882
883 \begin_layout Plain Layout
884
885 x=rnorm(5)
886 \end_layout
887
888 \begin_layout Plain Layout
889
890 x
891 \end_layout
892
893 \begin_layout Plain Layout
894
895 var(x)
896 \end_layout
897
898 \begin_layout Plain Layout
899
900 @
901 \end_layout
902
903 \end_inset
904
905
906 \end_layout
907
908 \begin_layout Standard
909 The example below shows the effect of
910 \family typewriter
911 tidy=TRUE/FALSE
912 \family default
913 :
914 \end_layout
915
916 \begin_layout Standard
917 \begin_inset ERT
918 status open
919
920 \begin_layout Plain Layout
921
922 <<tidy-no, eval=FALSE, tidy=FALSE>>=
923 \end_layout
924
925 \begin_layout Plain Layout
926
927 ## option tidy=FALSE
928 \end_layout
929
930 \begin_layout Plain Layout
931
932 for(k in 1:10){j=cos(sin(k)*k^2)+3;print(j-5)}
933 \end_layout
934
935 \begin_layout Plain Layout
936
937 @
938 \end_layout
939
940 \begin_layout Plain Layout
941
942 <<tidy-yes, eval=FALSE, tidy=TRUE>>=
943 \end_layout
944
945 \begin_layout Plain Layout
946
947 ## option tidy=TRUE
948 \end_layout
949
950 \begin_layout Plain Layout
951
952 for(k in 1:10){j=cos(sin(k)*k^2)+3;print(j-5)}
953 \end_layout
954
955 \begin_layout Plain Layout
956
957 @
958 \end_layout
959
960 \end_inset
961
962
963 \end_layout
964
965 \begin_layout Standard
966 Note
967 \family typewriter
968 =
969 \family default
970 is replaced by
971 \family typewriter
972 <-
973 \family default
974 because
975 \family typewriter
976 options('formatR.arrow')
977 \family default
978 was set to be
979 \family typewriter
980 TRUE
981 \family default
982 in this document; see the documentation of
983 \emph on
984 tidy.source()
985 \emph default
986 in
987 \series bold
988 formatR
989 \series default
990 for details.
991 \end_layout
992
993 \begin_layout Standard
994 Many highlighting themes can be used in
995 \series bold
996 knitr
997 \series default
998 , which are borrowed from the
999 \series bold
1000 highlight
1001 \series default
1002 package by
1003 \begin_inset CommandInset href
1004 LatexCommand href
1005 name "Andre Simon"
1006 target "http://www.andre-simon.de/"
1007
1008 \end_inset
1009
1010
1011 \begin_inset Foot
1012 status open
1013
1014 \begin_layout Plain Layout
1015 not the R package mentioned before; for a preview of these themes, see
1016 \begin_inset Flex URL
1017 status collapsed
1018
1019 \begin_layout Plain Layout
1020
1021 http://www.andre-simon.de/dokuwiki/doku.php?id=theme_examples
1022 \end_layout
1023
1024 \end_inset
1025
1026
1027 \end_layout
1028
1029 \end_inset
1030
1031 ; it is also possible to use themes from
1032 \begin_inset Flex URL
1033 status collapsed
1034
1035 \begin_layout Plain Layout
1036
1037 http://www.eclipsecolorthemes.org/
1038 \end_layout
1039
1040 \end_inset
1041
1042 by providing a theme id to
1043 \series bold
1044 knitr
1045 \series default
1046
1047 \begin_inset Foot
1048 status open
1049
1050 \begin_layout Plain Layout
1051 many thanks to
1052 \begin_inset CommandInset href
1053 LatexCommand href
1054 name "Ramnath Vaidyanathan"
1055 target "https://github.com/ramnathv"
1056
1057 \end_inset
1058
1059 for the work on themes
1060 \end_layout
1061
1062 \end_inset
1063
1064 .
1065 See
1066 \family typewriter
1067 ?knit_theme
1068 \family default
1069 for details.
1070 \end_layout
1071
1072 \begin_layout Subsection
1073 Graphics
1074 \end_layout
1075
1076 \begin_layout Standard
1077 Graphics is an important part of reports, and several enhancements have
1078 been made in
1079 \series bold
1080 knitr
1081 \series default
1082 .
1083 For example, grid graphics may not need to be explicitly printed as long
1084 as the same code can produce plots in R (in some cases, however, they have
1085 to be printed, e.g.
1086 in a loop, because you have to do so in an R terminal).
1087 \end_layout
1088
1089 \begin_layout Subsubsection
1090 Graphical Devices
1091 \end_layout
1092
1093 \begin_layout Standard
1094 Over a long time, a frequently requested feature for Sweave was the support
1095 for other graphics devices, which has been implemented since R 2.13.0.
1096 Instead of using logical options like
1097 \family typewriter
1098 png
1099 \family default
1100 or
1101 \family typewriter
1102 jpeg
1103 \family default
1104 (this list can go on and on),
1105 \series bold
1106 knitr
1107 \series default
1108 uses a single option
1109 \family typewriter
1110 dev
1111 \family default
1112 (like
1113 \family typewriter
1114 grdevice
1115 \family default
1116 in Sweave) which has support for more than 20 devices.
1117 For instance,
1118 \family typewriter
1119 dev='png'
1120 \family default
1121 will use the
1122 \emph on
1123 png()
1124 \emph default
1125 device, and
1126 \family typewriter
1127 dev='CairoJPEG'
1128 \family default
1129 uses the
1130 \emph on
1131 CairoJPEG()
1132 \emph default
1133 device in the
1134 \series bold
1135 Cairo
1136 \series default
1137 package (it has to be installed first, of course).
1138 If none of these devices is satisfactory, you can provide the name of a
1139 customized device function, which must have been defined before it is called.
1140 \end_layout
1141
1142 \begin_layout Subsubsection
1143 Plot Recording
1144 \end_layout
1145
1146 \begin_layout Standard
1147 As mentioned before, all the plots in a code chunk are first recorded as
1148 R objects and then
1149 \begin_inset Quotes eld
1150 \end_inset
1151
1152 replayed
1153 \begin_inset Quotes erd
1154 \end_inset
1155
1156 inside a graphical device to generate plot files.
1157 The
1158 \series bold
1159 evaluate
1160 \series default
1161 package will record plots per
1162 \emph on
1163 expression
1164 \emph default
1165 basis, in other words, the source code is split into individual complete
1166 expressions and
1167 \series bold
1168 evaluate
1169 \series default
1170 will examine possible plot changes in snapshots after each single expression
1171 has been evaluated.
1172 For example, the code below consists of three expressions, out of which
1173 two are related to drawing plots, therefore
1174 \series bold
1175 evaluate
1176 \series default
1177 will produce two plots by default:
1178 \end_layout
1179
1180 \begin_layout Standard
1181 \begin_inset ERT
1182 status open
1183
1184 \begin_layout Plain Layout
1185
1186 <<low-level-plots, fig.keep='all', dev='tikz', fig.width=2.5, fig.height=2.5,
1187 out.width='.3
1188 \backslash
1189
1190 \backslash
1191 textwidth', cache=TRUE>>=
1192 \end_layout
1193
1194 \begin_layout Plain Layout
1195
1196 par(mar=c(3,3,.1,.1))
1197 \end_layout
1198
1199 \begin_layout Plain Layout
1200
1201 plot(1:10, ann=FALSE,las=1)
1202 \end_layout
1203
1204 \begin_layout Plain Layout
1205
1206 text(5,9,'mass $
1207 \backslash
1208
1209 \backslash
1210 rightarrow$ energy
1211 \backslash
1212 n$E=mc^2$')
1213 \end_layout
1214
1215 \begin_layout Plain Layout
1216
1217 @
1218 \end_layout
1219
1220 \end_inset
1221
1222
1223 \end_layout
1224
1225 \begin_layout Standard
1226 This brings a significant difference with traditional tools in R for dynamic
1227 report generation, since low-level plotting changes can also be recorded.
1228 The option
1229 \family typewriter
1230 fig.keep
1231 \family default
1232 controls which plots to keep in the output;
1233 \family typewriter
1234 fig.keep='all'
1235 \family default
1236 will keep low-level changes as separate plots; by default (
1237 \family typewriter
1238 fig.keep='high'
1239 \family default
1240 ),
1241 \series bold
1242 knitr
1243 \series default
1244 will merge low-level plot changes into the previous high-level plot, like
1245 most graphics devices do.
1246 This feature may be useful for teaching R graphics step by step.
1247 Note, however, low-level plotting commands in a single expression (a typical
1248 case is a loop) will not be recorded accumulatively, but high-level plotting
1249 commands, regardless of where they are, will always be recorded.
1250 For example, this chunk will only produce 2 plots instead of 21 plots because
1251 there are 2 complete expressions:
1252 \end_layout
1253
1254 \begin_layout Standard
1255 \begin_inset ERT
1256 status open
1257
1258 \begin_layout Plain Layout
1259
1260 <<low-plot-loop, eval=FALSE>>=
1261 \end_layout
1262
1263 \begin_layout Plain Layout
1264
1265 plot(0,0,type='n',ann=FALSE)
1266 \end_layout
1267
1268 \begin_layout Plain Layout
1269
1270 for(i in seq(0, 2*pi,length=20)) points(cos(i),sin(i))
1271 \end_layout
1272
1273 \begin_layout Plain Layout
1274
1275 @
1276 \end_layout
1277
1278 \end_inset
1279
1280
1281 \end_layout
1282
1283 \begin_layout Standard
1284 But this will produce 20 plots as expected:
1285 \end_layout
1286
1287 \begin_layout Standard
1288 \begin_inset ERT
1289 status open
1290
1291 \begin_layout Plain Layout
1292
1293 <<high-plot-loop, eval=FALSE>>=
1294 \end_layout
1295
1296 \begin_layout Plain Layout
1297
1298 for(i in seq(0, 2*pi,length=20)) {plot(cos(i),sin(i),xlim=c(-1,1),ylim=c(-1,1))}
1299 \end_layout
1300
1301 \begin_layout Plain Layout
1302
1303 @
1304 \end_layout
1305
1306 \end_inset
1307
1308
1309 \end_layout
1310
1311 \begin_layout Standard
1312 As I showed in the beginning of this manual, it is straightforward to let
1313
1314 \series bold
1315 knitr
1316 \series default
1317 keep all the plots in a chunk and insert them into the output document,
1318 so we no longer need the
1319 \family typewriter
1320 cat('
1321 \backslash
1322
1323 \backslash
1324 includegraphics{}')
1325 \family default
1326 trick.
1327 \end_layout
1328
1329 \begin_layout Standard
1330 We can discard all previous plots and keep the last one only by
1331 \family typewriter
1332 fig.keep='last'
1333 \family default
1334 , or keep only the first plot by
1335 \family typewriter
1336 fig.keep='first'
1337 \family default
1338 , or discard all plots by
1339 \family typewriter
1340 fig.keep='none'
1341 \family default
1342 .
1343 \end_layout
1344
1345 \begin_layout Subsubsection
1346 Plot Rearrangement
1347 \end_layout
1348
1349 \begin_layout Standard
1350 The option
1351 \family typewriter
1352 fig.show
1353 \family default
1354 can decide whether to hold all plots while evaluating the code and
1355 \begin_inset Quotes eld
1356 \end_inset
1357
1358 flush
1359 \begin_inset Quotes erd
1360 \end_inset
1361
1362 all of them to the end of a chunk (
1363 \family typewriter
1364 fig.show='hold'
1365 \family default
1366 ), or just insert them to the place where they were created (by default
1367
1368 \family typewriter
1369 fig.show='asis'
1370 \family default
1371 ).
1372 Here is an example of
1373 \family typewriter
1374 fig.show='asis'
1375 \family default
1376 :
1377 \end_layout
1378
1379 \begin_layout Standard
1380 \begin_inset ERT
1381 status open
1382
1383 \begin_layout Plain Layout
1384
1385 <<fig-hold, fig.show='asis', dev='pdf', fig.width=6, fig.height=4, out.width='.35
1386 \backslash
1387
1388 \backslash
1389 linewidth'>>=
1390 \end_layout
1391
1392 \begin_layout Plain Layout
1393
1394 contour(volcano) # contour lines
1395 \end_layout
1396
1397 \begin_layout Plain Layout
1398
1399 filled.contour(volcano) # fill contour plot with colors
1400 \end_layout
1401
1402 \begin_layout Plain Layout
1403
1404 @
1405 \end_layout
1406
1407 \end_inset
1408
1409
1410 \end_layout
1411
1412 \begin_layout Standard
1413 Beside
1414 \family typewriter
1415 hold
1416 \family default
1417 and
1418 \family typewriter
1419 asis
1420 \family default
1421 , the option
1422 \family typewriter
1423 fig.show
1424 \family default
1425 can take a third value:
1426 \family typewriter
1427 animate
1428 \family default
1429 , which makes it possible to insert animations into the output document.
1430 In LaTeX, the package
1431 \series bold
1432 animate
1433 \series default
1434 is used to put together image frames as an animation.
1435 For animations to work, there must be more than one plot produced in a
1436 chunk.
1437 The option
1438 \family typewriter
1439 interval
1440 \family default
1441 controls the time interval between animation frames; by default it is 1
1442 second.
1443 Note you have to add
1444 \family typewriter
1445
1446 \backslash
1447 usepackage{animate}
1448 \family default
1449 in the LaTeX preamble, because
1450 \series bold
1451 knitr
1452 \series default
1453 will not add it automatically.
1454 Animations in the PDF output can only be viewed in Adobe Reader.
1455 \end_layout
1456
1457 \begin_layout Standard
1458 As a simple demonstration, here is a
1459 \begin_inset CommandInset href
1460 LatexCommand href
1461 name "Mandelbrot animation"
1462 target "http://en.wikipedia.org/wiki/Mandelbrot_set"
1463
1464 \end_inset
1465
1466 taken from the
1467 \series bold
1468 animation
1469 \series default
1470 package
1471 \begin_inset CommandInset citation
1472 LatexCommand citep
1473 key "R-animation"
1474
1475 \end_inset
1476
1477 ; note the PNG device is used because PDF files are too large.
1478 You should be able to see the animation immediately with Acrobat Reader
1479 since it was set to play automatically:
1480 \end_layout
1481
1482 \begin_layout Standard
1483 \begin_inset ERT
1484 status open
1485
1486 \begin_layout Plain Layout
1487
1488 <<animate-demo, fig.show='animate', dev='png', out.width='.45
1489 \backslash
1490
1491 \backslash
1492 linewidth', interval=.5, aniopts='controls,loop,autoplay', cache=TRUE>>=
1493 \end_layout
1494
1495 \begin_layout Plain Layout
1496
1497 library(animation)
1498 \end_layout
1499
1500 \begin_layout Plain Layout
1501
1502 demo('Mandelbrot', echo = FALSE, package = 'animation')
1503 \end_layout
1504
1505 \begin_layout Plain Layout
1506
1507 @
1508 \end_layout
1509
1510 \end_inset
1511
1512
1513 \end_layout
1514
1515 \begin_layout Subsubsection
1516 Plot Size
1517 \end_layout
1518
1519 \begin_layout Standard
1520 The
1521 \family typewriter
1522 fig.width
1523 \family default
1524 and
1525 \family typewriter
1526 fig.height
1527 \family default
1528 options specify the size of plots in the graphics device, and the real
1529 size in the output document can be different (see
1530 \family typewriter
1531 out.width
1532 \family default
1533 and
1534 \family typewriter
1535 out.height
1536 \family default
1537 ).
1538 When there are multiple plots per chunk, it is possible to arrange more
1539 than one plot per line in LaTeX -- just specify
1540 \family typewriter
1541 out.width
1542 \family default
1543 to be less than half of the current line width, e.g.
1544
1545 \family typewriter
1546 out.width='.49
1547 \backslash
1548
1549 \backslash
1550 linewidth'
1551 \family default
1552 .
1553 \end_layout
1554
1555 \begin_layout Subsubsection
1556 The tikz Device
1557 \end_layout
1558
1559 \begin_layout Standard
1560 Beside PDF, PNG and other traditional R graphical devices,
1561 \series bold
1562 knitr
1563 \series default
1564 has special support to tikz graphics via the
1565 \series bold
1566 tikzDevice
1567 \series default
1568 package
1569 \begin_inset CommandInset citation
1570 LatexCommand citep
1571 key "R-tikzDevice"
1572
1573 \end_inset
1574
1575 , which is similar to
1576 \series bold
1577 pgfSweave
1578 \series default
1579 .
1580 If we set the chunk option
1581 \family typewriter
1582 dev='tikz'
1583 \family default
1584 , the
1585 \emph on
1586 tikz()
1587 \emph default
1588 device in
1589 \series bold
1590 tikzDevice
1591 \series default
1592 will be used to save plots.
1593 Options
1594 \family typewriter
1595 sanitize
1596 \family default
1597 and
1598 \family typewriter
1599 external
1600 \family default
1601 are related to the tikz device: see the documentation of
1602 \emph on
1603 tikz()
1604 \emph default
1605 for details.
1606 Note
1607 \family typewriter
1608 external=TRUE
1609 \family default
1610 in
1611 \series bold
1612 knitr
1613 \series default
1614 has a different meaning with
1615 \series bold
1616 pgfSweave
1617 \series default
1618 -- it means
1619 \family typewriter
1620 standAlone=TRUE
1621 \family default
1622 in
1623 \emph on
1624 tikz()
1625 \emph default
1626 , and the tikz graphics output will be compiled to PDF
1627 \emph on
1628 immediately
1629 \emph default
1630 after it is created, so the
1631 \begin_inset Quotes eld
1632 \end_inset
1633
1634 externalization
1635 \begin_inset Quotes erd
1636 \end_inset
1637
1638 does not depend on the
1639 \series bold
1640 tikz
1641 \series default
1642 package; to maintain consistency in (font) styles,
1643 \series bold
1644 knitr
1645 \series default
1646 will read the preamble of the input document and use it in the tikz device.
1647 At the moment, I'm not sure if this is a faithful way to externalize tikz
1648 graphics, but I have not seen any problems so far.
1649 The assumption to make, however, is that you declare all the styles in
1650 the preamble;
1651 \series bold
1652 knitr
1653 \series default
1654 is agnostic of
1655 \emph on
1656 local
1657 \emph default
1658 style changes in the body of the document.
1659 \end_layout
1660
1661 \begin_layout Standard
1662 Below is an example taken from StackOverflow
1663 \begin_inset Foot
1664 status open
1665
1666 \begin_layout Plain Layout
1667 \begin_inset Flex URL
1668 status collapsed
1669
1670 \begin_layout Plain Layout
1671
1672 http://stackoverflow.com/q/8190087/559676
1673 \end_layout
1674
1675 \end_inset
1676
1677
1678 \end_layout
1679
1680 \end_inset
1681
1682 ; we usually have to write R code like this to obtain a math expression
1683
1684 \begin_inset Formula $\mathrm{d}\mathbf{x}_{t}=\alpha[(\theta-\mathbf{x}_{t})\mathrm{d}t+4]\mathrm{d}B_{t}$
1685 \end_inset
1686
1687 in R graphics:
1688 \end_layout
1689
1690 \begin_layout Standard
1691 \begin_inset ERT
1692 status open
1693
1694 \begin_layout Plain Layout
1695
1696 <<math-expr-R, eval=FALSE>>=
1697 \end_layout
1698
1699 \begin_layout Plain Layout
1700
1701 qplot(1:10, 1:10) + opts(title = substitute(paste(d *
1702 \end_layout
1703
1704 \begin_layout Plain Layout
1705
1706 bolditalic(x)[italic(t)] == alpha * (theta - bolditalic(x)[italic(t)])
1707 *
1708 \end_layout
1709
1710 \begin_layout Plain Layout
1711
1712 d * italic(t) + lambda * d * italic(B)[italic(t)]), list(lambda = 4)))
1713
1714 \end_layout
1715
1716 \begin_layout Plain Layout
1717
1718 @
1719 \end_layout
1720
1721 \end_inset
1722
1723
1724 \end_layout
1725
1726 \begin_layout Standard
1727 With the tikz device, it is both straightforward and more beautiful:
1728 \end_layout
1729
1730 \begin_layout Standard
1731 \begin_inset ERT
1732 status open
1733
1734 \begin_layout Plain Layout
1735
1736 <<math-expr-tikz, dev='tikz', fig.width=5, fig.height=3, out.width='.55
1737 \backslash
1738
1739 \backslash
1740 linewidth', cache=TRUE, message=FALSE>>=
1741 \end_layout
1742
1743 \begin_layout Plain Layout
1744
1745 library(ggplot2)
1746 \end_layout
1747
1748 \begin_layout Plain Layout
1749
1750 qplot(1:10, 1:10) +
1751 \end_layout
1752
1753 \begin_layout Plain Layout
1754
1755 labs(title = sprintf('$
1756 \backslash
1757
1758 \backslash
1759 mathrm{d}
1760 \backslash
1761
1762 \backslash
1763 mathbf{x}_{t} =
1764 \backslash
1765
1766 \backslash
1767 alpha[(
1768 \backslash
1769
1770 \backslash
1771 theta -
1772 \backslash
1773
1774 \backslash
1775 mathbf{x}_{t})
1776 \backslash
1777
1778 \backslash
1779 mathrm{d}t + %d]
1780 \backslash
1781
1782 \backslash
1783 mathrm{d}B_{t}$', 4))
1784 \end_layout
1785
1786 \begin_layout Plain Layout
1787
1788 @
1789 \end_layout
1790
1791 \end_inset
1792
1793
1794 \end_layout
1795
1796 \begin_layout Standard
1797 The advantage of tikz graphics is the consistency of styles
1798 \begin_inset Foot
1799 status collapsed
1800
1801 \begin_layout Plain Layout
1802 Users are encouraged to read the vignette of
1803 \series bold
1804 tikzDevice
1805 \series default
1806 , which is the most beautiful vignette I have ever seen in R packages:
1807 \begin_inset Flex URL
1808 status collapsed
1809
1810 \begin_layout Plain Layout
1811
1812 http://cran.r-project.org/web/packages/tikzDevice/vignettes/tikzDevice.pdf
1813 \end_layout
1814
1815 \end_inset
1816
1817
1818 \end_layout
1819
1820 \end_inset
1821
1822 , and one disadvantage is that LaTeX may not be able to handle too large
1823 tikz files (it can run out of memory).
1824 For example, an R plot with tens of thousands of graphical elements may
1825 fail to compile in LaTeX if we use the tikz device.
1826 In such cases, we can switch to the PDF or PNG device, or reconsider our
1827 decision on the type of plots, e.g., a scatter plot with millions of points
1828 is usually difficult to read, and a contour plot or a hexagon plot showing
1829 the 2D density can be a better alternative (they are smaller in size).
1830 \end_layout
1831
1832 \begin_layout Standard
1833 The graphics manual contains more detailed information and you can check
1834 it out in the
1835 \begin_inset CommandInset href
1836 LatexCommand href
1837 name "website"
1838 target "https://yihui.org/knitr/demo/graphics/"
1839
1840 \end_inset
1841
1842 .
1843 \end_layout
1844
1845 \begin_layout Subsection
1846 Cache
1847 \end_layout
1848
1849 \begin_layout Standard
1850 The feature of cache is not a new idea -- both
1851 \series bold
1852 cacheSweave
1853 \series default
1854 and
1855 \series bold
1856 weaver
1857 \series default
1858 have implemented it based on Sweave, with the former using
1859 \series bold
1860 filehash
1861 \series default
1862 and the latter using
1863 \family sans
1864 .RData
1865 \family default
1866 images;
1867 \series bold
1868 cacheSweave
1869 \series default
1870 also supports lazy-loading of objects based on
1871 \series bold
1872 filehash
1873 \series default
1874 .
1875 The
1876 \series bold
1877 knitr
1878 \series default
1879 package directly uses internal base R functions to save (
1880 \emph on
1881 tools:::makeLazyLoadDB()
1882 \emph default
1883 ) and lazy-load objects (
1884 \emph on
1885 lazyLoad()
1886 \emph default
1887 ).
1888 These functions are either undocumented or marked as internal, but as far
1889 as I understand, they are the tools to implement lazy-loading for packages.
1890 The
1891 \series bold
1892 cacheSweave
1893 \series default
1894 vignette has clearly explained lazy-loading, and roughly speaking, lazy-loading
1895 means an object will not be really loaded into memory unless it is really
1896 used somewhere.
1897 This is very useful for cache; sometimes we read a large object and cache
1898 it, then take a subset for analysis and this subset is also cached; in
1899 the future, the initial large object will not be loaded into R if our computati
1900 on is only based on the object of its subset.
1901 \end_layout
1902
1903 \begin_layout Standard
1904 The paths of cache files are determined by the chunk option
1905 \family typewriter
1906 cache.path
1907 \family default
1908 ; by default all cache files are created under a directory
1909 \family sans
1910 cache
1911 \family default
1912 relative to the current working directory, and if the option value contains
1913 a directory (e.g.
1914
1915 \family typewriter
1916 cache.path='cache/abc-'
1917 \family default
1918 ), cache files will be stored under that directory (automatically created
1919 if it does not exist).
1920 The cache is invalidated and purged on any changes to the code chunk, including
1921 both the R code and chunk options
1922 \begin_inset Foot
1923 status open
1924
1925 \begin_layout Plain Layout
1926 One exception is the
1927 \family typewriter
1928 include
1929 \family default
1930 option, which is not cached because
1931 \family typewriter
1932 include=TRUE/FALSE
1933 \family default
1934 does not affect code evaluation; meanwhile, the value
1935 \family typewriter
1936 getOption('width')
1937 \family default
1938 is also cached, so if you change this option, the cache will also be invalidate
1939 d (this option affects the width of text output)
1940 \end_layout
1941
1942 \end_inset
1943
1944 ; this means previous cache files of this chunk are removed (filenames are
1945 identified by the chunk label).
1946 Unlike
1947 \series bold
1948 pgfSweave
1949 \series default
1950 , cache files will never accumulate since old cache files will always be
1951 removed in
1952 \series bold
1953 knitr
1954 \series default
1955 .
1956 Unlike
1957 \series bold
1958 weaver
1959 \series default
1960 or
1961 \series bold
1962 cacheSweave
1963 \series default
1964 ,
1965 \series bold
1966 knitr
1967 \series default
1968 will try to preserve these side-effects:
1969 \end_layout
1970
1971 \begin_layout Enumerate
1972 printed results: meaning that any output of a code chunk will be loaded
1973 into the output document for a cached chunk, although it is not really
1974 evaluated.
1975 The reason is
1976 \series bold
1977 knitr
1978 \series default
1979 also cache the output of a chunk as a character string.
1980 Note this means graphics output is also cached since it is part of the
1981 output.
1982 It has been a pain for me for a long time to have to lose output to gain
1983 cache;
1984 \end_layout
1985
1986 \begin_layout Enumerate
1987 loaded packages: after the evaluation of each cached chunk, the list of
1988 packages used in the current R session is written to a file under the cache
1989 path named
1990 \family sans
1991 __packages
1992 \family default
1993 ; next time if a cached chunk needs to be rebuilt, these packages will be
1994 loaded first.
1995 The reasons for caching package names are, it can be slow to load some
1996 packages, and a package might be loaded in a previous cached chunk which
1997 is not available to the next cached chunk when only the latter needs to
1998 be rebuilt.
1999 Note this only applies to cached chunks, and for uncached chunks, you must
2000 always use
2001 \emph on
2002 library()
2003 \emph default
2004 to load packages explicitly;
2005 \end_layout
2006
2007 \begin_layout Standard
2008 Although
2009 \series bold
2010 knitr
2011 \series default
2012 tries to keep some side-effects, there are still other types of side-effects
2013 like setting
2014 \emph on
2015 par()
2016 \emph default
2017 or
2018 \emph on
2019 options()
2020 \emph default
2021 which are not cached.
2022 Users should be aware of these special cases, and make sure to clearly
2023 separate the code which is not meant to be cached to other chunks which
2024 are not cached, e.g., set all global options in the first chunk of a document
2025 and do not cache that chunk.
2026 \end_layout
2027
2028 \begin_layout Standard
2029 Sometimes a cached chunk may need to use objects from other cached chunks,
2030 which can bring a serious problem -- if objects in previous chunks have
2031 changed, this chunk will not be aware of the changes and will still use
2032 old cached results, unless there is a way to detect such changes from other
2033 chunks.
2034 There is an option called
2035 \family typewriter
2036 dependson
2037 \family default
2038 in
2039 \series bold
2040 cacheSweave
2041 \series default
2042 which does this job.
2043 We can explicitly specify which other chunks this chunk depends on by setting
2044 an option like
2045 \family typewriter
2046 dependson='chunkA;chunkB'
2047 \family default
2048 or equivalently
2049 \family typewriter
2050 dependson=c('chunkA', 'chunkB')
2051 \family default
2052 .
2053 Each time the cache of a chunk is rebuilt, all other chunks which depend
2054 on this chunk will lose cache, hence their cache will be rebuilt as well.
2055 \end_layout
2056
2057 \begin_layout Standard
2058 Another way to specify the dependencies among chunks is to use the chunk
2059 option
2060 \family typewriter
2061 autodep
2062 \family default
2063 and the function
2064 \emph on
2065 dep_auto()
2066 \emph default
2067 .
2068 This is an experimental feature borrowed from
2069 \series bold
2070 weaver
2071 \series default
2072 which frees us from setting chunk dependencies manually.
2073 The basic idea is, if a latter chunk uses any objects created from a previous
2074 chunk, the latter chunk is said to depend on the previous one.
2075 The function
2076 \emph on
2077 find_globals()
2078 \emph default
2079 in the
2080 \series bold
2081 xfun
2082 \series default
2083 package is used to find out all global objects in a chunk, and according
2084 to its documentation, the result is an approximation.
2085 Global objects roughly mean the ones which are not created locally, e.g.
2086 in the expression
2087 \family typewriter
2088 function() {y <- x}
2089 \family default
2090 ,
2091 \family typewriter
2092 x
2093 \family default
2094 should be a global object, whereas
2095 \family typewriter
2096 y
2097 \family default
2098 is local.
2099 Meanwhile, we also need to save the list of objects created in each cached
2100 chunk, so that we can compare them to the global objects in latter chunks.
2101 For example, if chunk A created an object
2102 \family typewriter
2103 x
2104 \family default
2105 and chunk B uses this object, chunk B must depend on A, i.e.
2106 whenever A changes, B must also be updated.
2107 When
2108 \family typewriter
2109 autodep=TRUE
2110 \family default
2111 ,
2112 \series bold
2113 knitr
2114 \series default
2115 will write out the names of objects created in a cached chunk as well as
2116 those global objects in two files named
2117 \family sans
2118 __objects
2119 \family default
2120 and
2121 \family sans
2122 __globals
2123 \family default
2124 respectively; later we can use the function
2125 \emph on
2126 dep_auto()
2127 \emph default
2128 to analyze the object names to figure out the dependencies automatically.
2129 See
2130 \begin_inset Flex URL
2131 status collapsed
2132
2133 \begin_layout Plain Layout
2134
2135 https://yihui.org/knitr/demo/cache/
2136 \end_layout
2137
2138 \end_inset
2139
2140 for examples.
2141 \end_layout
2142
2143 \begin_layout Standard
2144 Yet another way to specify dependencies is
2145 \emph on
2146 dep_prev()
2147 \emph default
2148 : this is a conservative approach which sets the dependencies so that a
2149 cached chunk will depend on all its previous chunks, i.e.
2150 whenever a previous chunk is updated, all later chunks will be updated
2151 accordingly.
2152 \end_layout
2153
2154 \begin_layout Subsection
2155 Code Externalization
2156 \end_layout
2157
2158 \begin_layout Standard
2159 It can be more convenient to write R code in a separate file, rather than
2160 mixing it into a LaTeX document; for example, we can run R code successively
2161 in a pure R script from one chunk to the other without jumping through
2162 other texts.
2163 Since I prefer using LyX to write reports, Sweave is even more inconvenient
2164 because I have to recompile the whole document each time, even if I only
2165 want to know the results of a single chunk.
2166 Therefore
2167 \series bold
2168 knitr
2169 \series default
2170 introduced the feature of code externalization to a separate R script.
2171 Currently the setting is like this: the R script also uses chunk labels
2172 (marked in the form
2173 \family typewriter
2174 ## ---- chunk-label
2175 \family default
2176 by default); if the code chunk in the input document is empty,
2177 \series bold
2178 knitr
2179 \series default
2180 will match its label with the label in the R script to input external R
2181 code.
2182 For example, suppose this is a code chunk labelled as
2183 \family typewriter
2184 Q1
2185 \family default
2186 in an R script named
2187 \family sans
2188 homework1-xie.R
2189 \family default
2190 which is under the same directory as the Rnw document:
2191 \end_layout
2192
2193 \begin_layout Standard
2194 \begin_inset ERT
2195 status open
2196
2197 \begin_layout Plain Layout
2198
2199 <<ext-r-code, eval=FALSE>>=
2200 \end_layout
2201
2202 \begin_layout Plain Layout
2203
2204 ## ---- Q1 ---------------------
2205 \end_layout
2206
2207 \begin_layout Plain Layout
2208
2209 gcd = function(m, n) {
2210 \end_layout
2211
2212 \begin_layout Plain Layout
2213
2214 while ((r <- m %% n) != 0) {
2215 \end_layout
2216
2217 \begin_layout Plain Layout
2218
2219 m = n; n = r
2220 \end_layout
2221
2222 \begin_layout Plain Layout
2223
2224 }
2225 \end_layout
2226
2227 \begin_layout Plain Layout
2228
2229 n
2230 \end_layout
2231
2232 \begin_layout Plain Layout
2233
2234 }
2235 \end_layout
2236
2237 \begin_layout Plain Layout
2238
2239 @
2240 \end_layout
2241
2242 \end_inset
2243
2244
2245 \end_layout
2246
2247 \begin_layout Standard
2248 In the Rnw document, we can first read the script using the function
2249 \emph on
2250 read_chunk()
2251 \emph default
2252 :
2253 \end_layout
2254
2255 \begin_layout Standard
2256 \begin_inset ERT
2257 status open
2258
2259 \begin_layout Plain Layout
2260
2261 <<read-chunk, eval=FALSE>>=
2262 \end_layout
2263
2264 \begin_layout Plain Layout
2265
2266 read_chunk('homework1-xie.R')
2267 \end_layout
2268
2269 \begin_layout Plain Layout
2270
2271 @
2272 \end_layout
2273
2274 \end_inset
2275
2276
2277 \end_layout
2278
2279 \begin_layout Standard
2280 This is usually done in an early chunk, and we can use the chunk
2281 \family typewriter
2282 Q1
2283 \family default
2284 later in the Rnw document:
2285 \end_layout
2286
2287 \begin_layout Standard
2288 \begin_inset ERT
2289 status open
2290
2291 \begin_layout Plain Layout
2292
2293 <<use-ext-chunk, echo=FALSE, comment=NA>>=
2294 \end_layout
2295
2296 \begin_layout Plain Layout
2297
2298 cat('<<Q1, echo=TRUE, tidy=TRUE>>=','@',sep='
2299 \backslash
2300 n')
2301 \end_layout
2302
2303 \begin_layout Plain Layout
2304
2305 @
2306 \end_layout
2307
2308 \end_inset
2309
2310
2311 \end_layout
2312
2313 \begin_layout Standard
2314 Different documents can read the same R script, so the R code can be reusable
2315 across different input documents.
2316 \end_layout
2317
2318 \begin_layout Subsection
2319 Evaluation of Chunk Options
2320 \begin_inset CommandInset label
2321 LatexCommand label
2322 name "sub:conditional"
2323
2324 \end_inset
2325
2326
2327 \end_layout
2328
2329 \begin_layout Standard
2330 By default
2331 \series bold
2332 knitr
2333 \series default
2334 uses a new syntax to parse chunk options: it treats them as function arguments
2335 instead of a text string to be split to obtain option values.
2336 This gives the user much more power than the old syntax; we can pass arbitrary
2337 R objects to chunk options besides simple ones like
2338 \family typewriter
2339 TRUE
2340 \family default
2341 /
2342 \family typewriter
2343 FALSE
2344 \family default
2345 , numbers and character strings.
2346 The page
2347 \begin_inset Flex URL
2348 status collapsed
2349
2350 \begin_layout Plain Layout
2351
2352 https://yihui.org/knitr/demo/sweave/
2353 \end_layout
2354
2355 \end_inset
2356
2357 has given two examples to show the advantages of the new syntax.
2358 Here we show yet another useful application.
2359 \end_layout
2360
2361 \begin_layout Standard
2362 Before
2363 \series bold
2364 knitr
2365 \series default
2366 0.3, there was a feature named
2367 \begin_inset Quotes eld
2368 \end_inset
2369
2370 conditional evaluation
2371 \begin_inset Quotes erd
2372 \end_inset
2373
2374
2375 \begin_inset Foot
2376 status open
2377
2378 \begin_layout Plain Layout
2379 request from
2380 \begin_inset Flex URL
2381 status collapsed
2382
2383 \begin_layout Plain Layout
2384
2385 https://plus.google.com/u/0/116405544829727492615/posts/43WrRUffjzK
2386 \end_layout
2387
2388 \end_inset
2389
2390
2391 \end_layout
2392
2393 \end_inset
2394
2395 .
2396 The idea is, instead of setting chunk options
2397 \family typewriter
2398 eval
2399 \family default
2400 and
2401 \family typewriter
2402 echo
2403 \family default
2404 to be
2405 \family typewriter
2406 TRUE
2407 \family default
2408 or
2409 \family typewriter
2410 FALSE
2411 \family default
2412 (constants), their values can be controlled by global variables in the
2413 current R session.
2414 This enables
2415 \series bold
2416 knitr
2417 \series default
2418 to conditionally evaluate code chunks according to variables.
2419 For example, here we assign
2420 \family typewriter
2421 TRUE
2422 \family default
2423 to a variable
2424 \family typewriter
2425 dothis
2426 \family default
2427 :
2428 \end_layout
2429
2430 \begin_layout Standard
2431 \begin_inset ERT
2432 status open
2433
2434 \begin_layout Plain Layout
2435
2436 <<cond-variable>>=
2437 \end_layout
2438
2439 \begin_layout Plain Layout
2440
2441 dothis=TRUE
2442 \end_layout
2443
2444 \begin_layout Plain Layout
2445
2446 @
2447 \end_layout
2448
2449 \end_inset
2450
2451
2452 \end_layout
2453
2454 \begin_layout Standard
2455 In the next chunk, we set chunk options
2456 \family typewriter
2457 eval=dothis
2458 \family default
2459 and
2460 \family typewriter
2461 echo=!dothis
2462 \family default
2463 , both are valid R expressions since the variable
2464 \family typewriter
2465 dothis
2466 \family default
2467 exists.
2468 As we can see, the source code is hidden, but it was indeed evaluated:
2469 \end_layout
2470
2471 \begin_layout Standard
2472 \begin_inset ERT
2473 status open
2474
2475 \begin_layout Plain Layout
2476
2477 <<cond-out1, eval=dothis, echo=!dothis>>=
2478 \end_layout
2479
2480 \begin_layout Plain Layout
2481
2482 print('you cannot see my source because !dothis is FALSE')
2483 \end_layout
2484
2485 \begin_layout Plain Layout
2486
2487 @
2488 \end_layout
2489
2490 \end_inset
2491
2492
2493 \end_layout
2494
2495 \begin_layout Standard
2496 Then we set
2497 \family typewriter
2498 eval=dothis
2499 \family default
2500 and
2501 \family typewriter
2502 echo=dothis
2503 \family default
2504 for another chunk:
2505 \end_layout
2506
2507 \begin_layout Standard
2508 \begin_inset ERT
2509 status open
2510
2511 \begin_layout Plain Layout
2512
2513 <<cond-out2,eval=dothis,echo=dothis>>=
2514 \end_layout
2515
2516 \begin_layout Plain Layout
2517
2518 dothis
2519 \end_layout
2520
2521 \begin_layout Plain Layout
2522
2523 @
2524 \end_layout
2525
2526 \end_inset
2527
2528
2529 \end_layout
2530
2531 \begin_layout Standard
2532 If we change the value of
2533 \family typewriter
2534 dothis
2535 \family default
2536 to
2537 \family typewriter
2538 FALSE
2539 \family default
2540 , neither of the above chunks will be evaluated any more.
2541 Therefore we can control many chunks with a single variable, and present
2542 results selectively.
2543 \end_layout
2544
2545 \begin_layout Standard
2546 This old feature requires
2547 \series bold
2548 knitr
2549 \series default
2550 to treat
2551 \family typewriter
2552 eval
2553 \family default
2554 and
2555 \family typewriter
2556 echo
2557 \family default
2558 specially, and we can easily see that it is no longer necessary with the
2559 new syntax:
2560 \family typewriter
2561 eval=dothis
2562 \family default
2563 will tell R to find the variable
2564 \family typewriter
2565 dothis
2566 \family default
2567 automatically just like we call a function
2568 \family typewriter
2569 foobar(eval = dothis)
2570 \family default
2571 .
2572 What is more, all options will be evaluated as R expressions unless they
2573 are already constants which do not need to be evaluated, so this old feature
2574 has been generalized to all other options naturally.
2575 \end_layout
2576
2577 \begin_layout Subsection
2578 Customization
2579 \end_layout
2580
2581 \begin_layout Standard
2582 The
2583 \series bold
2584 knitr
2585 \series default
2586 package is ready for customization.
2587 Both the patterns and hooks can be customized; see the package website
2588 for details.
2589 Here I show an example on how to save
2590 \series bold
2591 rgl
2592 \series default
2593 plots
2594 \begin_inset CommandInset citation
2595 LatexCommand citep
2596 key "R-rgl"
2597
2598 \end_inset
2599
2600 using a customized hook function.
2601 First we define a hook named
2602 \family typewriter
2603 rgl
2604 \family default
2605 using the function
2606 \emph on
2607 hook_rgl()
2608 \emph default
2609 in
2610 \series bold
2611 rgl
2612 \series default
2613 :
2614 \end_layout
2615
2616 \begin_layout Standard
2617 \begin_inset ERT
2618 status open
2619
2620 \begin_layout Plain Layout
2621
2622 <<rgl-demo>>=
2623 \end_layout
2624
2625 \begin_layout Plain Layout
2626
2627 library(rgl)
2628 \end_layout
2629
2630 \begin_layout Plain Layout
2631
2632 knit_hooks$set(rgl = hook_rgl)
2633 \end_layout
2634
2635 \begin_layout Plain Layout
2636
2637 head(hook_rgl) # the hook function is defined as this
2638 \end_layout
2639
2640 \begin_layout Plain Layout
2641
2642 @
2643 \end_layout
2644
2645 \end_inset
2646
2647
2648 \end_layout
2649
2650 \begin_layout Standard
2651 Then we only have to set the chunk option
2652 \family typewriter
2653 rgl=TRUE
2654 \family default
2655 :
2656 \end_layout
2657
2658 \begin_layout Standard
2659 \begin_inset ERT
2660 status open
2661
2662 \begin_layout Plain Layout
2663
2664 <<fancy-rgl, rgl=TRUE, dev='png', fig.width=5, fig.height=5, out.width='2in',
2665 message=FALSE, warning=FALSE, cache=TRUE>>=
2666 \end_layout
2667
2668 \begin_layout Plain Layout
2669
2670 library(rgl)
2671 \end_layout
2672
2673 \begin_layout Plain Layout
2674
2675 demo('bivar', package='rgl', echo=FALSE)
2676 \end_layout
2677
2678 \begin_layout Plain Layout
2679
2680 par3d(zoom=.7)
2681 \end_layout
2682
2683 \begin_layout Plain Layout
2684
2685 @
2686 \end_layout
2687
2688 \end_inset
2689
2690
2691 \end_layout
2692
2693 \begin_layout Standard
2694 Due to the flexibility of output hooks,
2695 \series bold
2696 knitr
2697 \series default
2698 supports several different output formats.
2699 The implementation is fairly easy, e.g., for LaTeX we put R output in
2700 \family typewriter
2701 verbatim
2702 \family default
2703 environments, and in HTML, it is only a matter of putting output in
2704 \family typewriter
2705 div
2706 \family default
2707 layers.
2708 These are simply character string operations.
2709 Many demos in
2710 \begin_inset Flex URL
2711 status collapsed
2712
2713 \begin_layout Plain Layout
2714
2715 https://yihui.org/knitr/demo/
2716 \end_layout
2717
2718 \end_inset
2719
2720 show this idea clearly.
2721 This manual did not cover all the features of
2722 \series bold
2723 knitr
2724 \series default
2725 , and users are encouraged to thumb through the website to know more possible
2726 features.
2727 \end_layout
2728
2729 \begin_layout Section
2730 Editors
2731 \end_layout
2732
2733 \begin_layout Standard
2734 You can use any text editors to write the source documents, but some have
2735 built-in support for
2736 \series bold
2737 knitr
2738 \series default
2739 .
2740 Both RStudio (
2741 \begin_inset Flex URL
2742 status collapsed
2743
2744 \begin_layout Plain Layout
2745
2746 http://www.rstudio.org
2747 \end_layout
2748
2749 \end_inset
2750
2751 ) and LyX (
2752 \begin_inset Flex URL
2753 status collapsed
2754
2755 \begin_layout Plain Layout
2756
2757 http://www.lyx.org
2758 \end_layout
2759
2760 \end_inset
2761
2762 ) have full support for
2763 \series bold
2764 knitr
2765 \series default
2766 , and you can compile the document to PDF with just one click.
2767 See
2768 \begin_inset Flex URL
2769 status collapsed
2770
2771 \begin_layout Plain Layout
2772
2773 https://yihui.org/knitr/demo/rstudio/
2774 \end_layout
2775
2776 \end_inset
2777
2778 and
2779 \begin_inset Flex URL
2780 status collapsed
2781
2782 \begin_layout Plain Layout
2783
2784 https://yihui.org/knitr/demo/lyx/
2785 \end_layout
2786
2787 \end_inset
2788
2789 respectively.
2790 It is also possible to support other editors like
2791 \begin_inset CommandInset href
2792 LatexCommand href
2793 name "Eclipse"
2794 target "https://yihui.org/knitr/demo/eclipse/"
2795
2796 \end_inset
2797
2798 ,
2799 \begin_inset CommandInset href
2800 LatexCommand href
2801 name "Texmaker and WinEdt"
2802 target "https://yihui.org/knitr/demo/editors/"
2803
2804 \end_inset
2805
2806 ; see the demo list in the website for configuration instructions.
2807 \end_layout
2808
2809 \begin_layout Section*
2810 About This Document
2811 \end_layout
2812
2813 \begin_layout Standard
2814 This manual was written in LyX and compiled with
2815 \series bold
2816 knitr
2817 \series default
2818 (version
2819 \begin_inset ERT
2820 status collapsed
2821
2822 \begin_layout Plain Layout
2823
2824
2825 \backslash
2826 Sexpr{packageVersion('knitr')}
2827 \end_layout
2828
2829 \end_inset
2830
2831 ).
2832 The LyX source and the Rnw document exported from LyX can be found under
2833 these directories:
2834 \end_layout
2835
2836 \begin_layout Standard
2837 \begin_inset ERT
2838 status open
2839
2840 \begin_layout Plain Layout
2841
2842 <<source-location, eval=FALSE>>=
2843 \end_layout
2844
2845 \begin_layout Plain Layout
2846
2847 system.file('examples', 'knitr-manual.lyx', package='knitr') # lyx source
2848 \end_layout
2849
2850 \begin_layout Plain Layout
2851
2852 system.file('examples', 'knitr-manual.Rnw', package='knitr') # Rnw source
2853 \end_layout
2854
2855 \begin_layout Plain Layout
2856
2857 @
2858 \end_layout
2859
2860 \end_inset
2861
2862
2863 \end_layout
2864
2865 \begin_layout Standard
2866 You can use the function
2867 \emph on
2868 knit()
2869 \emph default
2870 to knit the Rnw document (remember to put the two
2871 \family sans
2872 .bib
2873 \family default
2874 files under the same directory), and you need to make sure all the R packages
2875 used in this document are installed:
2876 \end_layout
2877
2878 \begin_layout Standard
2879 \begin_inset ERT
2880 status open
2881
2882 \begin_layout Plain Layout
2883
2884 <<required-packages, eval=FALSE>>=
2885 \end_layout
2886
2887 \begin_layout Plain Layout
2888
2889 install.packages(c('animation', 'rgl', 'tikzDevice', 'ggplot2'))
2890 \end_layout
2891
2892 \begin_layout Plain Layout
2893
2894 @
2895 \end_layout
2896
2897 \end_inset
2898
2899
2900 \end_layout
2901
2902 \begin_layout Standard
2903 Feedback and comments on this manual and the package are always welcome.
2904 Bug reports and feature requests can be sent to
2905 \begin_inset Flex URL
2906 status collapsed
2907
2908 \begin_layout Plain Layout
2909
2910 https://github.com/yihui/knitr/issues
2911 \end_layout
2912
2913 \end_inset
2914
2915 , and questions can be delivered to the
2916 \begin_inset CommandInset href
2917 LatexCommand href
2918 name "mailing list"
2919 target "[email protected]"
2920 type "mailto:"
2921
2922 \end_inset
2923
2924
2925 \begin_inset Flex URL
2926 status collapsed
2927
2928 \begin_layout Plain Layout
2929
2930 https://groups.google.com/group/knitr
2931 \end_layout
2932
2933 \end_inset
2934
2935 .
2936 \end_layout
2937
2938 \begin_layout Standard
2939 \begin_inset ERT
2940 status open
2941
2942 \begin_layout Plain Layout
2943
2944 % when knitr is updated, this chunk will be updated; why?
2945 \end_layout
2946
2947 \begin_layout Plain Layout
2948
2949 <<auto-bib, version=packageVersion('knitr'), echo=FALSE, cache=TRUE, message=FAL
2950 SE, warning=FALSE>>=
2951 \end_layout
2952
2953 \begin_layout Plain Layout
2954
2955 # write all packages in the current session to a bib file
2956 \end_layout
2957
2958 \begin_layout Plain Layout
2959
2960 write_bib(c(.packages(), 'evaluate', 'formatR', 'highr'), file = 'knitr-packages.b
2961 ib')
2962 \end_layout
2963
2964 \begin_layout Plain Layout
2965
2966 @
2967 \end_layout
2968
2969 \end_inset
2970
2971
2972 \end_layout
2973
2974 \begin_layout Standard
2975 \begin_inset CommandInset bibtex
2976 LatexCommand bibtex
2977 bibfiles "knitr-manual,knitr-packages"
2978 options "jss"
2979
2980 \end_inset
2981
2982
2983 \end_layout
2984
2985 \end_body
2986 \end_document