F Using R Markdown

ds4psy: R Markdown primer

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, 2024b) and rmarkdown (Allaire et al., 2024), both of which are included in a standard installation of RStudio.

Motivation

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).83 Thanks to R Markdown (Xie, Allaire, & Grolemund, 2018), we can adopt this paradigm and harvest its benefits.

References

Allaire, J., Xie, Y., Dervieux, C., McPherson, J., Luraschi, J., Ushey, K., … Iannone, R. (2024). 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. (2024b). 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/

  1. Fun fact: The original paper by Donald Knuth proposes a programming language and documentation system called WEB years before CERN introduced the World Wide Web.↩︎