Literate programming

Jeff Stevens



Mental model of file directories

File types

Computer files

All files are collections of 1s and 0s

Plain text

  • Only characters with no formatting

  • Viewable in text editor

  • Used for plain text storage (.txt, .csv) and coding (.R, .Rmd, .py, .m, .cpp)


  • 1s and 0s are converted to images, audio, formatted text


  • Binary document files: .docx, .xlsx, .pptx, .pdf, .png, .jpg

Interacting with R

Interacting with R

  • Console

  • R scripts (.R)

  • R Markdown files (.Rmd)




Run commands

Line-by-line or selected code


All code above cursor


All code below cursor



Run commands

Sourcing runs whole script



Comments are not executed by R

2+2 # this is a comment--I can say stuff that isn't run. use me often!
# this is also a comment--I can be on my own line!

Let’s code!

  • Open course RStudio project.

  • Create new R script and save as test.R.

  • Type library(palmerpenguins).

  • Is palmerpenguins loaded? How can you check?

  • Run the line to load palmerpenguins.

  • Type print(penguins).

  • Source the whole script.

  • Comment out the print(penguins) line.

  • Source the script.

Literate programming

Literate programming

An article [. . . ] in a scientific publication is not the scholarship itself, it is merely advertising of the scholarship. The actual scholarship is the complete software development environment and the complete set of instructions which generated the figures — Buckheit & Donoho (1995)

Why use literate programming?

  1. Direct connection between computations and presentation

  2. Updating presentation is a breeze

  3. Transparent and reproducible

  4. Plain text less corruptable

  5. Easily create different kinds of output styles and files

  6. Easily switch between different templates

Mental model of R Markdown


Human-readable markup that can be converted to formatted file types


See Markdown tutorial for Markdown syntax


Markdown uses HTML syntax for comments

<!-- comment here -->

Visual editor

R Markdown

Human-readable markup that embeds R code and output into formatted file types

From text to document

Inline R code

Embed R code directly within your text with `r `


The answer to 2 + 2 is `r 2 + 2`


The answer to 2 + 2 is 4.

R code chunks

Write large chunks of R code outside of text


rnorm(10, mean = 0, sd = 1)


 [1]  1.07226361  0.28961309  0.51448089  0.02877086  1.16809879 -0.77932607
 [7]  0.16475254  0.26947219 -1.15918876  1.02495565

Embed figures

plot(1:10, 2:11)

Mental model of R Markdown

Let’s code!

  • Create new R Markdown file.

  • Type “The mean of the first 9 digits is `r mean(1:9)`.

  • Knit/render the document.

  • Create a new code chunk.

  • Inside the code chunk, load the palmerpenguins package and print the penguins data set.

  • Run the code chunk without knitting the file.

  • Knit/render the file.