F Using R Markdown
This appendix explains why and how to use R Markdown for merging text and code and for easily creating beautiful documents (in HTML or PDF format). Using R Markdown requires installing the R packages knitr (Xie, 2020b) and rmarkdown (Allaire et al., 2020), both of which are included in a standard installation of RStudio.
The practitioner of literate programming can be regarded as an essayist,
whose main concern is with exposition and excellence of style.
Donald E. Knuth (1984), Literate Programming
The basic motivation behind R Markdown is simple: We normally do not want to converse in code, but tell a good story that may use data, code, and visualizations to support our argument. This basic state of affairs holds true not only for student homework assignments, but also for dissertations, scientific reports, and books. But when it comes to programming, separating content and form requires a reversal of our traditional way of interacting with computers: We no longer want to write programs or scripts in which we insert occasional comments (which need to be marked to prevent the computer from interpreting them). Instead, we want to write text that occasionally uses snippets of code to calculate or summarize something.
Ideally, we should be able to interleave our narrative with programming code in a single, but hybrid document. To benefit from such a mix of text and code, we need to invoke a dynamic process that interprets (or “knits”) our hybrid source document and creates an output document that merges our text, code, and the results of running our code (e.g., tables and images) into a report. This simple, but powerful paradigm is called literate programming and now over 35 years old (Knuth, 1984).71 Thanks to R Markdown (Xie, Allaire, & Grolemund, 2018), we can adopt this paradigm and harvest its benefits.
Allaire, J. J., Xie, Y., McPherson, J., Luraschi, J., Ushey, K., Atkins, A., … Iannone, R. (2020). rmarkdown: Dynamic documents for R. Retrieved from https://github.com/rstudio/rmarkdown
Knuth, D. E. (1984). Literate programming. The Computer Journal, 27(2), 97–111. https://doi.org/10.1093/comjnl/27.2.97
Xie, Y. (2020b). knitr: A general-purpose package for dynamic report generation in R. Retrieved from https://yihui.org/knitr/
Xie, Y., Allaire, J. J., & Grolemund, G. (2018). R Markdown: The definitive guide. Retrieved from https://bookdown.org/yihui/rmarkdown/
Fun fact: The original paper by Donald Knuth proposes a programming language and documentation system called
WEByears before CERN introduced the World Wide Web.↩