F Using R Markdown
This appendix explains why and how to use R Markdown for mixing and merging text and code. This requires installing the R packages rmarkdown (Allaire et al., 2020) and knitr (Xie, 2020b), which are both included in standard installations of R Studio.
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 for books, dissertations, scientific reports, and student homework assignments. But when it comes to programming computers, it requires a reversal of our traditional way of interacting with them: We no longer want to write programming 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).65 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://CRAN.R-project.org/package=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://CRAN.R-project.org/package=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.↩