Skip to main content

Section B.4 Parts of an R Markdown File

R Markdown is very similar to a traditional R script, but it has more rules and sections. Here, we will be breaking down the different sections.

Subsection B.4.1 The YAML

At the top of the document you will find what is called the YAML, which contains the metadata for the document. It has four default components:
  • title: What the title of your R Markdown is.
  • author: Who the author is (you).
  • date: The date of the R Markdown (defaults to the date of your computer).
  • output: The output you designated the document to be created into
    • There are some cool things you can add here, like change the overall theme or add TOC (table of contents). Like anything in R, take some time to explore and experiment with this.
You’ll also notice that the YAML is contained within ---. Besides being at the top of the document, this is R’s way of knowing that this specific part of the document is the YAML.

Subsection B.4.2 Text

In an R script, every line is dedicated to writing code, with you having to specifically use a # to denote otherwise (as a reminder, in R code, a # comments out whatever is on that line, whether code or text). That is different in R Markdown.
Instead of the default being R code, anything you write in a document is treated as text. This is incredibly useful when you want to:
For instance, what you’re reading right now is text inside an R Markdown file. There is no special way of telling R in an R Markdown file that this is text, because it by default knows that this is text.
There are, though, ways to tell R we want to edit text.

Subsubsection B.4.2.1 Styling Text

Just like in any document, sometimes we want to make particular pieces of text look different. The two most common ways are, and how to accomplish this in R Markdown, are:
Italic: to do this, add * to the beginning and end of your text (whether a single letter, word, sentence, paragraph, etc.).
*It will look like this.*
Bold: to do this, add ** to the beginning and end of your text (whether a single letter, word, sentence, paragraph, etc.).
**It will look like this.**
These are the two basic ways to edit text. What if we need to indent in order to create a list?

Subsubsection B.4.2.2 Adding Lists

As with traditional documents, R Markdown is able to create lists, whether that is numbered or bulleted. In order to create a bulleted list, a - and then a space between the text is needed. For a numbered list, you need the number, then a period, then a space before your text. Below are examples of both.
- Text
- More text

1. Text
2. More text
We have seen both of these ample times throughout this textbook, and also in this chapter!
Now that we have talked more about the text portions of an R Markdown, let’s now talk about the code portions.

Subsection B.4.3 R Chunks

Similar to how the YAML used the --- to enclose whatever was inside, for R chunks, R Markdown uses "```". Whatever is inside an R chunk is treated as R code.
Additionally, each R chunk has {}, and inside of that bracket is the letter "r". This is telling R that inside this chunk is going to be some code in the coding language R.
It is typically best practice to also name your R chunks. Each one should be a unique name, not only for a way for you to distinguish them from each other, but for R to distinguish them as well. To name your R chunk, you write right next to the "r", like this:
{r name-of-chunk}
It is best practice to either use one long word or use a - in between your words. In each R Markdown document, there are two major types of R chunks.

Subsubsection B.4.3.1 Setup Chunk

In a brand new R Markdown document, you will see what is called the "Setup" R chunk. Besides its position just below the YAML, the word "setup" is written, with some code from the knitr package. The setup chunk is used to define global options that apply to all code chunks in the document, such as whether code is shown or hidden.
Most of the time you do not have to do anything to this code, so we will leave it. Now, it is time to actually write some R code.

Subsubsection B.4.3.2 Chunks for R Code

It has already been established that in order to write R code, you need to create an R chunk. Inside an R chunk, you are able to code as normally as you would in an R script. The same rules (even adding comments) apply inside an R chunk. Think of each R chunk as a mini R script.
Take the code below. This, as well as all of the code in the book is written inside R chunks. Below is some code that is from all the way back from section SubsectionΒ 2.5.8 of the book.
library(tidyverse)
library(palmerpenguins)

penguins_new <- penguins %>%
  select(species, island, bill_length_mm, body_mass_g) %>%
  filter(species == "Adelie") %>%
  mutate(size_category = if_else(body_mass_g >= 3500, "Big","Small")) %>%
  arrange(desc(body_mass_g)) %>%
  rename(penguin_types = species)
This code works just as it did in the third chapter. In the R Markdown document, all of the code shows. This is an example of how now, for anyone looking, they are able to see your code.
What if we want them to see not only the code, but the output? All we have to do is call what we want to be displayed! For instance, if we want to display the square root of 25:
sqrt(25)
[1] 5
With the above R code, our R Markdown file shows both the sqrt(25) code as well as the answer (5).
This is the same no matter if its square root, ANOVAs, linear regressions, and anything else in this chapter. The only difference is how tables and graphs are displayed.
Tables.
Let’s go back to that penguins_new dataset. Before in section SubsubsectionΒ B.4.3.2, we "created" it. Now, let’s see what happens when we call the output.
penguins_new
# A tibble: 152 Γ— 5
   penguin_types island    bill_length_mm body_mass_g size_category
   <fct>         <fct>              <dbl>       <int> <chr>        
 1 Adelie        Biscoe              43.2        4775 Big          
 2 Adelie        Biscoe              41          4725 Big          
 3 Adelie        Torgersen           42.9        4700 Big          
 4 Adelie        Torgersen           39.2        4675 Big          
 5 Adelie        Dream               39.8        4650 Big          
 6 Adelie        Dream               39.6        4600 Big          
 7 Adelie        Biscoe              45.6        4600 Big          
 8 Adelie        Torgersen           42.5        4500 Big          
 9 Adelie        Dream               37.5        4475 Big          
10 Adelie        Torgersen           41.8        4450 Big          
# β„Ή 142 more rows
By calling penguins_new, the R Markdown document now displays the output, which in this case is penguins_new.
Now, that works, but in R Markdown, there is an even better way to display tables. Using the knitr package, we can display tables with the kable() function, which is purposely dedicated to displaying tabular data in R Markdown.
library(knitr)
kable(head(penguins_new), caption = "This is an example of displaying a table using the kable command. On top of the data looking nicer then just a regular output, we can add a caption (and manipulate other aesthetic pieces.")
Table: This is an example of displaying a table using the kable command. On top of the data looking nicer then just a regular output, we can add a caption (and manipulate other aesthetic pieces.

|penguin_types |island    | bill_length_mm| body_mass_g|size_category |
|:-------------|:---------|--------------:|-----------:|:-------------|
|Adelie        |Biscoe    |           43.2|        4775|Big           |
|Adelie        |Biscoe    |           41.0|        4725|Big           |
|Adelie        |Torgersen |           42.9|        4700|Big           |
|Adelie        |Torgersen |           39.2|        4675|Big           |
|Adelie        |Dream     |           39.8|        4650|Big           |
|Adelie        |Dream     |           39.6|        4600|Big           |
If we compare and contrast the output from just penguins_new vs the output from the kable() function, there is a stark difference. One of the most important differences is that you can add a caption that can illuminate the table more than just a simple output.
In the code above, we could have just called penguins_new and not just the head() of penguins_new, so why did we do this?
If we did not call head() then kable() would have produced a table displaying all rows from penguins_new, which would have the user scrolling for a long time. It is always your call as the creator of the document, but keep this in mind:
You don’t always have to show all your data.
By calling head(), your audience still gets a good picture of what your data looks like.
Graphs.
In R Markdown, just how we can display tables, we can also display graphs. Similar to the kable() function for tables, we can utilize fig.cap to both index and provide a caption for graphs. The major difference between kable() and fig.cap is that kable() goes into the actual R chunk, while fig.cap goes in the top {} of the R chunk.
# {r example-ggplot2, fig.cap="An example of a visualization made using ggplot2."}
ggplot(data = mpg, aes(x = cty, y = hwy)) +
  geom_point()
A scatterplot with city mileage on the x-axis and highway mileage on the y-axis, showing a positive relationship between the two variables across 234 vehicles in the mpg dataset.
Figure B.4.1. An example of a visualization made using ggplot2. This scatterplot displays the relationship between city mileage (cty) and highway mileage (hwy) from the mpg dataset.
This visualization, which we originally built in Section SubsectionΒ 3.4.2, not only displays the data, but provides a caption to explain the visualization, all thanks to fig.cap.
Yes, a picture is worth 1,000 words, but sometimes it can be helpful to add some words to help guide viewers.

Subsection B.4.4 Sections

One of the most important and powerful parts of an R Markdown document is it’s ability to organize elements into Sections.
Do you see how this chapter, and each chapter of the textbook, are broken down into sections like 10.1, 3.7, etc? Each number represents a different section of the document.
R Markdown utilizes the # symbol to set up sections. Here is an example:
# Section 1
# Section 2
## Section 2.1
Notice that a hierarchy is determined through the number of # in the header. Each additional # means one level lower.