[size=1.2em]For beginners, it is probably a good idea to start with some minimal examples; here I provide a few examples for Rnw, LaTeX, Markdown and HTML, respectively.
How is a report generated from R code[size=1.2em]Regardless of which format you use, the basic idea is the same: knitr extracts R code in the input document, evaluates it and writes the results to the output document. There are two types of R code: chunks (code as separate paragraphs) and inline R code. For example, here we show a code chunk (using traditional Sweave syntax):
Example text outside R code here; we know the value of pi is \Sexpr{pi}.<<my-label, eval=TRUE, dev='png'>>=set.seed(1213) # for reproducibilityx = cumsum(rnorm(100))mean(x) # mean of xplot(x, type = 'l') # Brownian motion@Other text outside R code here.[size=1.2em]After weaving this chunk, we get the output as below. Compare them and you will realize the inline code \Sexpr{pi} is replaced by the value of pi, and the code chunk is also evaluated – numerical results are printed and plots are inserted in the output as well.
Example text outside R code here; we know the value of pi is 3.1415926.set.seed(1213) # for reproducibilityx = cumsum(rnorm(100))mean(x) # mean of x## [1] -1.939758plot(x, type = 'l') # Brownian motion[size=1.2em]
Other text outside R code here.[size=1.2em]Now hopefully you have got an idea of how automatic report generation works. There are many options of which we can make use to tune the results, for example, we can use echo=FALSEto hide the R souce code (usually you do not want R code to appear in a final report, unless you are writing a tutorial on R), or results='hide' to hide the printed results (e.g. you will not see ## [1] -1.939758 above if you use this option), or control the format, size and alignment of plots. Beside local chunk options which you write between << and >>=, you can also set options globally like:
knitr::opts_chunk$set(echo=FALSE, fig.path='myproject/plot-', cache=TRUE)[size=1.2em]Once options are set globally, all the following chunks will be affected by these options, so if you use an option frequently in many chunks, you may want to set it globally.
[size=1.2em]The advantage of using knitr is obvious: you only maintain the source code, and whenever you want a report, you just knit the source code, and everything will be generated automatically (tables, plots and numbers in lines). There is no need to manually copy and paste anything. Next time if you data source is changed, you simply run the process again, and all results can be updated. Let computers do the tedious job, because this is what they are good at. Humans should focus on other jobs like the statistical analysis and organization of the report.