knitr
for generating dynamic documents that include text, code, and results.knitr
?knitr
is an R package that allows you to organize your notes, code, and results in a single document. It’s a great tool for “literate programming” – the idea that your code should be readable by humans as well as computers! It also keeps your writing and results together, so if you collect some new data or change how you clean the data, you just have to re-compile the document and you’re up to date!
You write knitr
documents in a simple plain text-like format called markdown, which allows you to format text using intuitive notation, so that you can focus on the content you’re writing and generating a well-formatted document when needed. In fact, you can turn your plain text (and R code and results into an HTML file or, if you have an installation of LaTeX and [Pandoc][pandoc] on your machine, a PDF, or even a Word document (if you must!.
To get started, install the knitr
package.
When you click on File -> New File, there is an option for “R Markdown…”. Choose this and accept the default options in the dialog box that follows (but note that you can also create presentations this way). Save the file and click on the “Knit HTML” button at the top of the script. Compare the output to the source.
Visit https://rmarkdown.rstudio.com/authoring_basics.html and briefly check out some of the formatting options. In the example document add
#
*
and numbered lists using 1.
, 2.
, etc.Markdown also supports LaTeX equation editing. We can display pretty equations by enclosing them in $
, e.g., $\alpha = \dfrac{1}{(1 - \beta)^2}$
renders as: \(\alpha = \dfrac{1}{(1 - \beta)^2}\)
The top of the source (.Rmd) file has some header material in YAML format (enclosed by triple dashes). Some of this gets displayed in the output header, other of it provides formatting information to the conversion engine.
To distinguish R code from text, RMarkdown uses three back-ticks followed by {r}
to distinguish a “code chunk”. In RStudio, the keyboard shortcut to create a code chunk is Command+Option+I or Ctrl+Alt+I.
A code chunk will set off the code and its results in the output document, but you can also print the results of code within a text block by enclosing code like so: r code-here
.
knit
the document and view the html result.{% include links.md %}
{r}
.