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, 2021) and rmarkdown (Allaire et al., 2021), 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, p. 97), 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).81 Thanks to R Markdown (Xie, Allaire, & Grolemund, 2018), we can adopt this paradigm and harvest its benefits.
Fun fact: The original paper by Donald Knuth proposes a programming language and documentation system called
WEByears before CERN introduced the World Wide Web.↩︎