Welcome to Spring Semester 2025.

Using R Markdown

R Markdown is regular Markdown with R code and output sprinkled in. You can do everything you can with regular Markdown, but you can incorporate graphs, tables, and other R output directly in your document. You can create HTML, PDF, and Word documents, PowerPoint and HTML presentations, websites, books, and even interactive dashboards with R Markdown. This whole course website is created with R Markdown (and a package named blogdown).

The documentation for R Markdown is extremely comprehensive, and their tutorials and cheatsheets are excellent—rely on those.

I have created a video walkthrough for using R Markdown for another course, but it is useful here. You can see it here ]

Here are the most important things you’ll need to know about R Markdown in this class:

Key terms

  • Document: A Markdown file where you type stuff

  • Chunk: A piece of R code that is included in your document. It looks like this:

    
    ```{r}
    # Code goes here
    ```

    There must be an empty line before and after the chunk. The final three backticks must be the only thing on the line—if you add more text, or if you forget to add the backticks, or accidentally delete the backticks, your document will not knit correctly.

  • Knit: When you “knit” a document, R runs each of the chunks sequentially and converts the output of each chunk into Markdown. R then runs the knitted document through pandoc to convert it to HTML or PDF or Word (or whatever output you’ve selected). We will always use PDF for this course.

    You can knit by clicking on the “Knit” button at the top of the editor window, or by pressing ⌘⇧K on macOS or control + shift + K on Windows.

    ::: {.cell} ::: {.cell-output-display} ::: :::

Add chunks

There are three ways to insert chunks:

  • Press ⌘⌥I on macOS or control + alt + I on Windows

  • Click on the “Insert” button at the top of the editor window

    ::: {.cell} ::: {.cell-output-display} ::: :::

  • Manually type all the backticks and curly braces (don’t do this)

Chunk names

You can add names to chunks to make it easier to navigate your document. If you click on the little dropdown menu at the bottom of your editor in RStudio, you can see a table of contents that shows all the headings and chunks. If you name chunks, they’ll appear in the list. If you don’t include a name, the chunk will still show up, but you won’t know what it does.

To add a name, include it immediately after the {r in the first line of the chunk. Names cannot contain spaces, but they can contain underscores and dashes. All chunk names in your document must be unique.

```{r name-of-this-chunk}
# Code goes here
```

Chunk options

There are a bunch of different options you can set for each chunk. You can see a complete list in the RMarkdown Reference Guide or at knitr’s website.

Options go inside the {r} section of the chunk:

```{r name-of-this-chunk, warning=FALSE, message=FALSE}
# Code goes here
```

The most common chunk options are these:

  • fig.width=5 and fig.height=3 (or whatever number you want): Set the dimensions for figures
  • echo=FALSE: The code is not shown in the final document, but the results are
  • message=FALSE: Any messages that R generates (like all the notes that appear after you load a package) are omitted
  • warning=FALSE: Any warnings that R generates are omitted
  • include=FALSE: The chunk still runs, but the code and results are not included in the final document. Don’t use this on your labs as we need to see your work, but do use this for your final project when the output is to be polished and clean.

You can also set chunk options by clicking on the little gear icon in the top right corner of any chunk:

Chunk fig.width and fig.height

When a code chunk includes a plot (like from ggplot), the “canvas” size used can affect the output. You may have noticed if you plot directly in Rstudio, the plot resizes when you change the pane size. Each chunk has its own canvas size, and you can change that. So, if you have a chunk with a large plot, you can change the fig.width=7.5 in the chunk options. Note that units default to inches, so no more than 7.5 will fit on a regular-sized sheet of paper (or appropriately sized PDF).

Inline chunks

You can also include R output directly in your text, which is really helpful if you want to report numbers from your analysis. To do this, use `r r_code_here`.

It’s generally easiest to calculate numbers in a regular chunk beforehand and then use an inline chunk to display the value in your text. For instance, this document…

```{r find-avg-mpg, echo=FALSE}
avg_mpg <- mean(mtcars$mpg)
```

The average fuel efficiency for cars from 1974 was `r round(avg_mpg, 1)` miles per gallon.

… would knit into this:

The average fuel efficiency for cars from 1974 was 20.1 miles per gallon.

Output formats

You can specify what kind of document you create when you knit in the YAML front matter.

title: "My document"
output:
  html_document: default
  pdf_document: default
  word_document: default

You can also click on the down arrow on the “Knit” button to choose the output and generate the appropriate YAML. If you click on the gear icon next to the “Knit” button and choose “Output options”, you change settings for each specific output type, like default figure dimensions or whether or not a table of contents is included.

The first output type listed under output: will be what is generated when you click on the “Knit” button or press the keyboard shortcut (⌘⇧K on macOS; control + shift + K on Windows). If you choose a different output with the “Knit” button menu, that output will be moved to the top of the output section.

The indentation of the YAML section matters, especially when you have settings nested under each output type. Here’s what a typical output section might look like:

---
title: "My document"
author: "My name"
date: "January 13, 2020"
output: 
  html_document: 
    toc: yes
    fig_caption: yes
    fig_height: 8
    fig_width: 10
  pdf_document: 
    latex_engine: xelatex  # More modern PDF typesetting engine
    toc: yes
  word_document: 
    toc: yes
    fig_caption: yes
    fig_height: 4
    fig_width: 5
---

Adding graphics to an Rmarkdown file

From the web

If you are incorporating an image (.png or .jpg) from another site on the web, you can refer to the image directly *provided the web address ends in .png or .jpg or .gif. Google image search makes it a little hard to get directly to the image source, so click through a search until you get to the original image. Once you’re there, right-click on the image and select “Copy Image Address” (may vary by system). If you can paste the URL into a new window and get the image itself, you’re good to go with the instructions here. Some sites and formats do not host the images as a separate file – they may be generated by an app. For instance, if we go to https://msu.edu/students, the background image address is not available by right-clicking. But scrolling down, the image for the Student Information System is https://student.msu.edu/. In cases where the image address is not readily available, you’ll have to take a screenshot and use the instructions in the next section (or dig into the site code if you know how to do that sort of thing). Let’s work on getting this image into our output: https://msu.edu/-/media/assets/msu/images/audience-student/students-sis-home.jpg.

Note that using a web address for an image means if the image owner changes the address or removes the image, you won’t be able to re-knit your document. See the next section for downloading the image and inserting into your document.

There are two ways of inserting an image: in markdown text, or in a code chunk. Both work. I prefer using the code chunk method, which uses knitr::include_graphics. This is an R function, so you use it inside a code chunk. When you are including an image inside a code chunk, the code chunk options can be used to control the fig.width or fig.height, and fig.align. For instance, fig.width = '75%' will use 75% of the available page width, whatever it may be. The down side is that you have to pull a copy of the image from the web and save it locally (earlier versions of Rmarkdown would do this for you automatically, but this feature was removed in rmarkdown v1.6 for security reasons). Here’s the code to do so:

Images inserted in code chunks

```{r, fig.width = '75%', fig.align='center', echo = TRUE}
download.file("https://msu.edu/-/media/assets/msu/images/audience-student/students-sis-home.jpg", destfile = 'temporary.jpg', mode='wb')
knitr::include_graphics(path = 'temporary.jpg')
```

The file you specify with destfile doesn’t matter - R will create that file, but you do need to use the corresponding suffix (don’t use temporary.jpg if you’re downloading a .png). By default, the file will be saved in the same folder as your .rmd file. When include_graphics goes to read the file, it will start looking relative to the folder that contains your .rmd file. That is, download.file will copy the image to the same place that include_graphics looks for it. See below for more on relative filepaths.

Note the code chunk option set above as well - fig.width='75%', which is stated in the curly-brackets that head the chunk. This is where Knitr finds details about how you want to handle the output. Before, we saw that echo=T would add a copy of the code itself to the output (vs. echo=F which output only the result). Similarly, fig.width='75%' should size the output to take up about 75% of the text width. You can also use fig.width=8 to set the output to 8 inches wide (closet to the width of a sheet of paper), which will maximize the space used for your plot. You may need this if/when you start plotting larger things. Hint.

Images inserted via Markdown

The markdown language is what controls the text outside of the R code chunks. It has its own way of inserting images. Here the image is inserted in the text, not in a code chunk.

![](https://msu.edu/-/media/assets/msu/images/audience-student/students-sis-home.jpg")

Images from a local file

Whether you have the file on your hard drive already, right-click and download from the web to keep a copy for posterity, or save the image from a screenshot, you will often need to insert an image from a local file. In Rmarkdown, the path will always be relative to the folder containing your .Rmd file. So if you keep your .Rmd in /Users/jkirk/SSC442/Example3 and you have a folder /Users/jkirk/SSC442/Example3/images that contains a file picture.png, then you would tell Rmarkdown to find the file at ./images/picture.png (which implies its filepath is /Users/jkirk/SSC442/Example3/images/picture.png). The ./ tells R to start looking in the local directory holding the .Rmd file you’re working on.

Once you know your local relative path, you can use either of the above methods knitr::include_graphics('./images/picture.png') or ![](./images/picture.png).

It is possible for R to find your image with an incorrect filepath when you click the “run chunk” button, but then not be able to find it when you knit. This can be very frustrating. It is almost always because you do not have the right relative filepath.