2 Adding code

The magic of R Markdown is that we can add code within our document to make it dynamic.

We do this either as code chunks (generally used for loading libraries and data, performing calculations, and adding images, plots, and tables), or inline code (generally used for dynamically reporting results within our text).

2.1 Code chunks

The syntax of a code chunk is shown in Figure 2.1.

Code chunk syntax

Figure 2.1: Code chunk syntax

Common chunk options include (see e.g. bookdown.org):

  • echo: whether or not to display code in knitted output
  • eval: whether or to to run the code in the chunk when knitting
  • include: wheter to include anything from the from a code chunk in the output document
  • fig.cap: figure caption
  • fig.scap: short figure caption, which will be used in the ‘List of Figures’ in the PDF front matter

IMPORTANT: Do not use underscoores in your chunk labels - if you do, you are likely to get an error in PDF output saying something like “! Package caption Error: \caption outside float.”

2.1.1 Setup chunks

An R Markdown document usually begins with a chunk that is used to load libraries, and to set default chunk options with knitr::opts_chunk$set.

In your thesis, this will probably happen in index.Rmd and/or as opening chunks in each of your chapters.

```{r setup, include=FALSE}
# don't show code unless we explicitly set echo = TRUE
knitr::opts_chunk$set(echo = FALSE)

library(tidyverse)
```

2.1.2 Including images

Code chunks are also used for including images, with include_graphics from the knitr package, as in Figure 2.2

knitr::include_graphics("figures/beltcrest.png")
Oxford logo

Figure 2.2: Oxford logo

Useful chunk options for figures include:

  • out.width (use with a percentage) for setting the image size
  • if you’ve got an image that gets waaay to big in your output, it will be constrained to the page width by setting out.width = "100%"

2.1.2.1 Control figure placement

Figure rotation

You can use the chunk option out.extra to rotate images.

The syntax is different for LaTeX and HTML, so for ease we might start by assigning the right string to a variable that depends on the format you’re outputting to:

if (knitr::is_latex_output()){
  rotate180 <- "angle=180"
} else {
  rotate180 <- "style='transform:rotate(180deg);'"
}

Then you can reference that variable as the value of out.extra to rotate images, as in Figure 2.3.

Oxford logo, rotated

Figure 2.3: Oxford logo, rotated

2.1.3 Including plots

Similarly, code chunks are used for including dynamically generated plots. You use ordinary code in R or other languages - Figure 2.4 shows a plot of the cars dataset of stopping distances for cars at various speeds (this dataset is built in to R).

cars %>% 
  ggplot() +
    aes(x = speed, y = dist) +
    geom_point()
A ggplot of car stuff

Figure 2.4: A ggplot of car stuff

Under the hood, plots are included in your document in the same way as images - when you build the book or knit a chapter, the plot is automatically generated from your code, saved as an image, then included into the output document.

2.1.4 Including tables

Tables are usually included with the kable function from the knitr package.

Table 2.1 shows the first rows of that cars data - read in your own data, then use this approach to automatically generate tables.

cars %>% 
  head() %>% 
  knitr::kable(caption = "A knitr kable table")
Table 2.1: A knitr kable table
speed dist
4 2
4 10
7 4
7 22
8 16
9 10
  • Gotcha: when using kable, captions are set inside the kable function
  • The kable package is often used with the kableExtra package

2.1.5 Control positioning

One thing that may be annoying is the way R Markdown handles “floats” like tables and figures. In your PDF output, LaTeX will try to find the best place to put your object based on the text around it and until you’re really, truly done writing you should just leave it where it lies.

In general, you should allow LaTeX to do this, but if you really really need a figure to be positioned where you put in the document, then you can make LaTeX attempt to do this with the chunk option fig.pos="H", as in Figure 2.5:

knitr::include_graphics("figures/beltcrest.png")
An Oxford logo that LaTeX will try to place at this position in the text

Figure 2.5: An Oxford logo that LaTeX will try to place at this position in the text

As anyone who has tried to manually play around with the placement of figures in a Word document knows, this can have lots of side effects with extra spacing on other pages, etc. Therefore, it is not generally a good idea to do this - only do it when you really need to ensure that an image follows directly under text where you refer to it (in this document, I needed to do this for Figure 4.1 in section 4.1.4). For more details, read the relevant section of the [R Markdown Cookbook]https://bookdown.org/yihui/rmarkdown-cookbook/figure-placement.html).

2.2 Inline code

‘Inline code’ simply means inclusion of code inside text. The syntax for doing this is `r R_CODE` For example, `r 4 + 4` will output 8 in your text.

You will usually use this in parts of your thesis where you report results - read in data or results in a code chunk, store things you want to report in a variable, then insert the value of that variable in your text. For example, we might assign the number of rows in the cars dataset to a variable:

num_car_observations <- nrow(cars)

We might then write:
“In the cars dataset, we have `r num_car_observations` observations.”

Which would output:
“In the cars dataset, we have 50 observations.”

2.2.1 Referring to results computed in other languages than R

I’ve commented the below section out, to avoid compilation errors from the reticulate package being unable to find a python installation (after I installed MacOS Catalina, reticulate was unable to select a python version on my system, and I had to set it manually with use_python).

If you need to use other langauges, have a look at the content I commented out by the end of the 02-rmd-basics-code.Rmd file, which gives an example of using Python in your R Markdown file.