2 + 2
#> [1] 4
If you find any typos, errors, or places where the text may be improved, please let us know by providing feedback either in the feedback survey (given during class) or by using GitHub.
On GitHub open an issue or submit a pull request by clicking the " Edit this page" link at the side of this page.
Session objectives:
Now, we will create and save a Quarto file. We’ll use the Command Palette by typing Ctrl-Shift-P
and then typing “quarto” and select the one that says “Create a new Quarto document”. You can also use the menu, by going to File -> New File -> Quarto Document ...
, and a dialog box will then appear. Enter”Reproducible documents” in the title field and your name in the author field. HTML should be automatically selected as the output format. There’s also the option to use the “visual mode”. This mode is great if you are used to working with Word and you can test it out on your own later. For this course, we will focus on using the normal mode.
After clicking “Create”, the new file will open in RStudio. You will see some text that gives a brief overview of how to use the Quarto file. For now, let’s ignore the text. At the top of the file you will see something that looks a bit like this:
---
title: "Reproducible documents"
author: "Your Name"
format: html
---
This section is called the YAML header and it contains the metadata about the document and the settings for how to process it into another document. Most Markdown documents have this YAML header at the top of the document and they are always surrounded by ---
on the top and bottom of the section. YAML is a data format that has the form of a key: value
pairing to store data. The keys in this case are title
, author
, and format
. The values are those that follow the key (e.g. “Your Name” for author
). In the case of Quarto, these key
data are used to store the settings that Quarto will use to create the format
output document. The keys listed above are some of many settings that R Markdown has available to use.
In the case of this YAML header, the Quarto document will generate an HTML file because of the format: html
setting. You can also create a word document by changing this to format: docx
. You can also create PDF documents, though this requires installing LaTeX through the R package tinytex, which can sometimes be complicated to install. We will only cover HTML and Word documents in this course. Before continuing, let’s save this file as learning.qmd
in the doc/
folder.
So, how do we create a HTML (or Word) document from the this document? We do that by “rendering” it. At the top of the pane near the “Save” button, there is a button with the word “Render” (if it’s R Markdown, it will be called “Knit” with a yarn symbol beside it). To render, you either click that button or use the shortcut Ctrl-Shift-K
anywhere in the R Markdown document.
When you click the “Render” button, a bunch of processing messages should appear in a new pane beside the Console, followed by a new window popping up with the newly created document. Alternatively, the HTML document may pop up in the “Viewer” pane.
You’ve now created a HTML document! Let’s try making a Word document. Change the YAML value in the key format:
from html
to docx
. Then render the document again with the “Render” button or Ctrl-Shift-K
for “Knit” (or using the Command Palette with Ctrl-Shift-P
, then type “render”). A Word document should open up. This is the basic approach to creating documents from R Markdown or Quarto. Before continuing, let’s add and commit the newly created file into the Git history (Ctrl-Shift-P
, then type “commit”).
Being able to insert R code directly into a document is one of the most powerful features of R Markdown. This frees you from having to switch between programs when simultaneously writing text and running R code to derive output that you’d then put into your manuscript.
Running and including R code in R Markdown is done using “R code chunks”. You insert these chunks into the document by placing the cursor at the location where you want the chunk to be, then using the shortcut Ctrl-Alt-I
for “Insert” or the menu item Code -> Insert Chunk
to insert a new code chunk. Like with everything else, you can also use the Command Palette with Ctrl-Shift-P
, then type “chunk”). Before we do that, let’s delete all the text in your document, with exception of the YAML header (including the dashes surrounding it). Make sure that the YAML key format:
is set to html
.
Then, place your cursor two lines below the YAML header and insert a code chunk (Ctrl-Alt-I
for “Insert” or Ctrl-Shift-P
, then type “chunk”). The code chunk should look something like this:
```{r}
```
In the code chunk, type out 2 + 2
, so it looks like:
```{r}
2 + 2
```
You can run R code inside the code chunk the same way as you would write it in an R script. Typing Ctrl-Enter
on the line will send the code 2 + 2
to the console, with the output appearing directly below the code chunk in the document. Note that this output is temporary.
To ensure that the output is inserted into the HTML document, render (Ctrl-Shift-K
or Ctrl-Shift-P
, then type “render”) the document and see what happens in the resulting HTML document. The output 4
should appear below the code chunk in the HTML document, something like this:
2 + 2
#> [1] 4
This is a very simple example of how code chunks work. Things are usually more complicated than this though. Normally, we have to load R packages to use for our subsequent code, and this is no different in an R Markdown document. We will set this up together now.
Create a new code chunk (Ctrl-Alt-I
for “Insert” or Ctrl-Shift-P
, then type “chunk”) and then type setup
right after the r
. It should look like:
```{r setup}
```
This area that you just typed ‘setup’ in is for code chunk labels. In this case, we labelled the code chunk with the name setup
. Code chunk labels should be named without _
, spaces, or .
and instead should be one word or be separated by -
. An error may not necessarily occur if you don’t follow this rule, but there can be unintended side effects that you may not realize and R will likely not tell you about it, probably causing you quite a bit of annoyance and frustration. Note, you can’t use duplicate code chunk labels in your document.
A nifty thing about using chunk labels is that you can get an overview of your code chunks using the “Document Outline” (found using Ctrl-Shift-O
), but only if you have this option set up in: Tools -> Global Options -> R Markdown -> Show in document outline
. These settings can also be found with the Command Palette (Ctrl-Shift-P
) followed by typing “document outline”.
The name setup
also has a special meaning for R Markdown. When you run other code chunks in the document, R Markdown will know to first look for and run the code in the setup
chunk. Therefore, this is a good place to put your library()
calls or other setup functions. Let’s enter some code to load the packages and the dataset we have been using to the setup chunk:
```{r setup}
library(tidyverse)
library(NHANES)
<- read_csv(here::here("data/nhanes_small.csv"))
nhanes_small ```
Let’s insert another code chunk below this one (Ctrl-Alt-I
for “Insert” or Ctrl-Shift-P
, then type “chunk”), and simply put nhanes_small
in the chunk:
```{r}
nhanes_small```
#> # A tibble: 10,000 × 8
#> age sex bmi diabetes phys_active bp_sys_ave bp_dia_ave
#> <dbl> <chr> <dbl> <chr> <chr> <dbl> <dbl>
#> 1 34 male 32.2 No No 113 85
#> 2 34 male 32.2 No No 113 85
#> 3 34 male 32.2 No No 113 85
#> 4 4 male 15.3 No <NA> NA NA
#> 5 49 female 30.6 No No 112 75
#> 6 9 male 16.8 No <NA> 86 47
#> 7 8 male 20.6 No <NA> 107 37
#> 8 45 female 27.2 No Yes 118 64
#> 9 45 female 27.2 No Yes 118 64
#> 10 45 female 27.2 No Yes 118 64
#> # ℹ 9,990 more rows
#> # ℹ 1 more variable: education <chr>
Let’s run this code as we normally would in a script file, by placing the cursor over the code and using the shortcut Ctrl-Enter
. We can also render (Ctrl-Shift-K
for “Knit” or Ctrl-Shift-P
, then type “render”) the document and see what it looks like. When the HTML document opens, you should see some text below the setup
chunk that might look something like this:
── Attaching packages ──────────────────────── tidyverse 1.3.2 ──
✔ ggplot2 3.4.0 ✔ purrr 1.0.0
✔ tibble 3.1.8 ✔ dplyr 1.0.10
✔ tidyr 1.2.1 ✔ stringr 1.5.0
✔ readr 2.1.3 ✔ forcats 0.5.2
── Conflicts ─────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag() masks stats::lag()
You probably don’t want this text in your generated document, so we will add a chunk option to remove this message. Chunk options are used to change how code chunks work. When adding them inside the code chunk, they always need to start with #|
. If you want to run the code but not show those messages and warnings, you can add the options #| message: false
and #| warning: false
:
```{r setup}
#| message: false
#| warning: false
library(tidyverse)
library(NHANES)
<- read_csv(here::here("data/nhanes_small.csv"))
nhanes_small ```
If you want to hide the code, messages, warnings, and output, but still run the code, you can use the option #| include: false
.
```{r setup}
#| include: false
library(tidyverse)
library(NHANES)
<- read_csv(here::here("data/nhanes_small.csv"))
nhanes_small ```
Other common options are:
echo
: To show the code. Default value is true
. Use false
to hide.results
: To show the output. Default is markup
. Use hide
to hide or asis
as regular text (not inside a code block).eval
: To evaluate (run) the R code in the chunk. Default value is true
, while false
does not run the code.These options all work on the individual code chunk. If you want to set an option to all the code chunks (e.g. to hide all the code but keep the output), you can use Quarto’s execute
options. These options are added to the YAML header and will apply the settings to everything in the document. We won’t do this in this session, but here is what it looks like:
---
title: "Reproducible documents"
author: "Your Name"
format: html
execute:
echo: false
warning: false
message: false
---
Let’s try running some R code to get Quarto to create a table. First, create a new header1 ## Table of results
and a new code chunk with the label mean-age-bmi-table
. Second, copy the code we worked on from the Data Wrangling session, in Section 7.15, which is shown below for you to copy from. Instead of using phys_active
, let’s change that to education
.
1 A “header” is something like a Chapter in books, or section titles in manuscripts like “Introduction” or “Results”.
```{r mean-age-bmi-table}
%>%
nhanes_small filter(!is.na(diabetes)) %>%
group_by(diabetes, education) %>%
summarise(
mean_age = mean(age, na.rm = TRUE),
mean_bmi = mean(bmi, na.rm = TRUE)
%>%
) ungroup()
```
#> # A tibble: 12 × 4
#> diabetes education mean_age mean_bmi
#> <chr> <chr> <dbl> <dbl>
#> 1 No 8th Grade 51.8 28.8
#> 2 No 9 - 11th Grade 46.3 28.6
#> 3 No College Grad 46.0 27.3
#> 4 No High School 46.1 28.9
#> 5 No Some College 43.8 28.7
#> 6 No <NA> 10.1 20.5
#> 7 Yes 8th Grade 63 32.0
#> 8 Yes 9 - 11th Grade 61.4 33.1
#> 9 Yes College Grad 60.6 31.3
#> 10 Yes High School 59.6 33.8
#> 11 Yes Some College 58.9 33.0
#> 12 Yes <NA> 16.7 26.1
Putting the cursor somewhere in the code, use the shortcut Ctrl-Enter
to run the code and see what it looks like. This output is almost in a table format. We have the columns that would be the table headers and rows that would be meaningful table rows. Ideally, we would want this to be report-ready. The first thing we should remove are the NA
education rows, just like we did with diabetes
. Then, we’ll convert it into a more elegant table in the R Markdown HTML output document, we use the kable()
function from the knitr package. Because we don’t want to load all of the knitr functions, we’ll use knitr::kable()
instead:
nhanes_small %>%
filter(!is.na(diabetes), !is.na(education)) %>%
group_by(diabetes, education) %>%
summarise(
mean_age = mean(age, na.rm = TRUE),
mean_bmi = mean(bmi, na.rm = TRUE)
) %>%
ungroup() %>%
knitr::kable(caption = "Mean values of Age and BMI for each education and diabetes status.")
diabetes | education | mean_age | mean_bmi |
---|---|---|---|
No | 8th Grade | 51.8 | 28.8 |
No | 9 - 11th Grade | 46.3 | 28.6 |
No | College Grad | 46.0 | 27.3 |
No | High School | 46.1 | 28.9 |
No | Some College | 43.8 | 28.7 |
Yes | 8th Grade | 63.0 | 32.0 |
Yes | 9 - 11th Grade | 61.4 | 33.1 |
Yes | College Grad | 60.6 | 31.3 |
Yes | High School | 59.6 | 33.8 |
Yes | Some College | 58.9 | 33.0 |
Now, render (Ctrl-Shift-K
for “Knit” or Ctrl-Shift-P
, then type “render”) and view the output in the HTML document. Pretty eh! Before continuing, let’s run styler (Ctrl-Shift-P
, then type “style file”) and then add and commit these changes into the Git history (Ctrl-Shift-P
, then type “commit”).
Time: ~20 minutes.
In the doc/learning.qmd
file, create a new header called ## Prettier table
along with a code chunk and label it prettier-table
. Copy the code below (that includes some code we wrote above) and paste the code into the new chunk. Add the option #| echo: false
to the code chunk.
```{r prettier-table}
%>%
nhanes_small filter(!is.na(diabetes), !is.na(education)) %>%
group_by(diabetes, education) %>%
summarise(
mean_age = mean(age, na.rm = TRUE),
mean_bmi = mean(bmi, na.rm = TRUE)
%>%
) ungroup() %>%
mutate(
# Task 2a.
___ = ___(mean_age, ___),
___ = ___(mean_bmi, ___),
# Task 2b.
___ = ___(education)
%>%
) rename(
# Task 3.
"___" = ___,
"___" = ___,
"___" = ___,
"___" = ___
%>%
) ::kable(caption = "Mean values of Age and BMI for each education and diabetes status.")
knitr```
Use mutate()
to perform the following wrangling tasks:
Rename diabetes
to "Diabetes Status"
, education
to Education
, and mean_age
and mean_bmi
to "Mean Age"
and "Mean BMI"
, using rename()
function. Hint: You can rename columns to include spaces by using "
around the new column name (e.g. "Diabetes Status" = diabetes
). Don’t forget, the renaming form is new = old
.
Run the code chunk to make sure the code works, including the knitr::kable()
function at the end of the pipe, with a table caption of your choice. If you want you can keep the same caption as is provided in the starting point below.
Run styler on the document (Ctrl-Shift-P
, then type “style file”).
Render the document to HTML (Ctrl-Shift-K
for “Knit” or Ctrl-Shift-P
, then type “render”) and see what the table looks like.
End the exercise by adding, committing, and pushing the files to your GitHub repository (Ctrl-Shift-P
, then type “commit”).
nhanes_small %>%
filter(!is.na(diabetes)) %>%
group_by(diabetes, education) %>%
summarise(
mean_age = mean(age, na.rm = TRUE),
mean_bmi = mean(bmi, na.rm = TRUE)
) %>%
ungroup() %>%
# 2. Round the means to 1 digit and
# modify the `education` column so that male and female get capitalized.
mutate(
mean_age = round(mean_age, 1),
mean_bmi = round(mean_bmi, 1),
education = str_to_sentence(education)
) %>%
# 3. Rename `diabetes` to `"Diabetes Status"` and `education` to `Education`
rename(
"Diabetes Status" = diabetes,
"Education" = education,
"Mean Age" = mean_age,
"Mean BMI" = mean_bmi
) %>%
knitr::kable(caption = "Mean values of Age and BMI for each education and diabetes status.")
For more details about other Markdown “syntax”, check out Appendix F as well as the R Markdown cheatsheet (
Tools -> Cheatsheets
) and Quarto’s Markdown Basics page. Continue to the exercise below.
Time: ~5 minutes.
Get some practice writing Markdown by completing these tasks in the doc/learning.qmd
file.
#
), called “Intro”, “Methods and Results”, and “Discussion”.##
) under “Methods and Results” called “Analysis”.**word**
) one word in each and italicize (*word*
) another.2 + 2
).Ctrl-Shift-P
, then type “commit”).Image files are always relative to the .qmd
file.
Render the document again (Ctrl-Shift-K
) and view the HTML document with the new picture. We can, if we want to, change the width and height of the image as well as its alignment. We do this by adding a {}
to the end of the Markdown image tag and put options inside there.
fig-align
: To align the figure, either in "center"
, "left"
, or "right"
.width
and height
: To set the image width and height for external images (not created by R). You can use percent to set the size as well, e.g. "75%"
.#fig-LABEL
: Use this to add a label so you can cross-reference it by typing inline @fig-LABEL
.For this image, we will change the width and height to "50%"
, and change the caption to something like "Kittens attacking flowers!"
, and add a label and reference:
Cute kitten in @fig-kitten-attack!
{#fig-kitten-attack width="50%" height="50%"}
Now in Figure 8.1, we see a kitten! Render again (Ctrl-Shift-K
for “Knit” or Ctrl-Shift-P
, then type “render”) to see how the image changes.
Time: 20 minutes.
Complete these tasks in the doc/learning.qmd
file.
doc/
.# Results
) and give it an appropriate caption.
Ctrl-Shift-K
for “Knit” or Ctrl-Shift-P
, then type “render”) to make sure the image gets inserted.theme
option in the YAML header and re-render the document (Ctrl-Shift-K
for “Knit” or Ctrl-Shift-P
, then type “render”).Ctrl-Shift-P
, then type “commit”). For now, don’t add and commit the HTML output file.knitr::kable()
# Header 1
), text formatting (**bold**
) and lists (-
) in the R Markdown file.
.