library(learnr) library(tutorial.helpers) library(tidyverse) library(knitr) knitr::opts_chunk$set(echo = FALSE) knitr::opts_chunk$set(out.width = '90%') options(tutorial.exercise.timelimit = 60, tutorial.storage = "local")
This tutorial covers Chapter 2 Workflow: basics, Chapter 4 Workflow: code style, Chapter 6 Workflow: scripts and projects, and some material from Chapter 28 Quarto from R for Data Science (2e) by Hadley Wickham, Mine Çetinkaya-Rundel, and Garrett Grolemund. You will learn how to create Quarto documents and how to publish your work to the web using Rpubs.
Quarto is a file format for making dynamic documents with R and other languages, like Python. To learn more about Quarto and how to use it, check out the official webpage. Quarto is the successor technology to R Markdown. This section introduces Quarto documents.
Click File -> New File -> Quarto Document...
at the top left of your RStudio window.
This will bring up the "New Quarto Document" box.
Add “My First Quarto Document” as the "Title". Add your name as the "Author".
Toward the bottom of the "New Quarto Document" box is the "Use visual markdown editor" check box. Make sure that this is not checked. Uncheck it if it is checked.
Click "Create."
Run list.files()
in the Console. CP/CR.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 2)
Since we have not saved the file yet, it does not appear in this listing.
Quarto is a command line interface tool, not an R package. This means that help is, by-and-large, not available through ?
at the R Console. Instead, as you work through this tutorial, and use Quarto in the future, you should refer to the Quarto documentation.
Save the Quarto document with File -> Save
. You can also click the disk icon toward the upper left of the Source pane or by use the shortcut Cmd/Ctrl + S
.
Name the file quarto-1
. The .qmd
file extension is added automatically.
Now that the document is saved, run list.files()
. CP/CR.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 2)
Somewhere in the output you should quarto-1.qmd
. That's the file you just made!
In the Console, run:
tutorial.helpers::show_file("quarto-1.qmd", end = 2)
CP/CR.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 3)
The argument end = 2
to show_file()
causes just the first two lines of quarto-1.qmd
to be printed.
Again, there is no necessary connection between the title of a Quarto document --- which is “My First Quarto Document” in this case --- and the name of the file --- which is quarto-1.qmd
.
In the top left corner above your Quarto document, you should see the buttons "Source", and "Visual". Click back and forth between them. Note how the display of the Quarto document changes.
Finish with "Source" selected.
The "Source" option displays our Quarto document in a similar fashion to our R scripts. We don't spend much time with the "Visual" option.
In the Console, run:
tutorial.helpers::show_file("quarto-1.qmd", start = -5)
CP/CR.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 3)
The start = -5
argument to show_file()
causes just the last 5 lines from quarto-1.Rmd
to be printed, with any empty lines removed.
Note the several different ways in which we use the word "Source":
The default Quarto file should look like this:
As you can see, a lot of the text is regular plain text, not code. However, there are code chunks (denoted by triple backticks on both ends, ```[code here]```) which allow us to execute code when the document is "rendered." (To "render" a Quarto document is to transform it into an html/pdf/docx or other output file format while also running any embedded code.) Here's an example of an R code chunk (note the triple backticks):
Quarto documents utilize Markdown (an easy-to-write plain text format), which can contain chunks of embedded code. These code chunks can be written in many languages, including R and Python. Code chunks allow you to use R to create plots and other graphics.
The YAML header is everything between the dashed lines at the top of the file, including the dashed lines themselves. Copy-and-paste the YAML header of the file below.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 4)
The YAML header includes "metadata" about the document itself, things like the title and the author. In this case, format: html
means that the document will be rendered as an HTML file.
Depending on your RStudio set up, the YAML header might include the line editor: visual
. This would tell RStudio, when opening the file on a new occasion, to set the editor to "Visual" mode. This is the same thing as pressing the "Visual" button. If this line is not present, don't worry about it. We recommend working in "Source" mode, at least at the start of your data science journey. Read this to learn more about the visual editor.
To "render" our Quarto document, click the "Render" arrow at the top of the Source pane, or use the shortcut Cmd/Ctrl + Shift + K
.
Run list.files()
. CP/CR.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 3)
You should see a new file, quarto-1.html
. This is the file created by rendering. The Viewer tab in the Output pane in the lower right of your workspace should also display the file.
You should also see a new directory: quarto-1_files
. Anytime you render a Quarto document, you create a directory like this, with the same name as the file plus _files
. Quarto uses this directory to store intermediate work products associated with the creation of the associated HTML files.
Note how the HTML document shows both the code 1 + 1
and the result of the addition. This is the magic of Quarto. We can easily document and reproduce our work. In quarto-1.qmd
, change 1 + 1
to 6 + 3
. Save the file. Render it again.
In the Console, run:
tutorial.helpers::show_file("quarto-1.qmd", pattern = "6")
CP/CR.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 17)
This should return a single character vector with "6 + 3"
, the line which you added to the file. Apologies for the complexity of the call needed to pull out that line.
Strictly speaking, you did not need to save the file before rendering it. Clicking the "Render" arrow saves the file automatically. Nevertheless, you should create a habit of saving your work before running (if you come across some software that doesn't autosave upon running, you'll be running old code and wondering why something still doesn't work when you just fixed it).
Delete everything except the YAML header, which is the text in the box at the top of the file, including the dashes. Add This is my first Markdown text.
two lines below the YAML header. Save the file.
In the Console, run:
tutorial.helpers::show_file("quarto-1.qmd")
CP/CR.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 3)
This should return your entire Quarto document. If you do not have an empty line at the end of your file, you will get a warning message like this:
Warning message: In readLines("quarto-1.qmd") : incomplete final line found on 'quarto-1.qmd'
The solution is to add an empty line to the end of the file. This is always a good idea! Don't be humble with whitespace.
Render the document. It is good to get in the practice of using the shortcut key Cmd/Ctrl + Shift + K
instead of the Render button. Efficient people use shortcut keys. They don't press buttons.
This will rewrite the current quarto-1.html
file, both in the current directory and in the Viewer pane.
In the following box, copy all of the text from your rendered Quarto document, from the Viewer tab within the Output pane.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 6)
Quarto files are designed to be used in three ways:
For communicating to decision-makers, who want to focus on the conclusions, not the code behind the analysis.
For collaborating with other data scientists (including future you!), who are interested in both your conclusions, and how you reached them (i.e. the code).
As an environment in which to do data science, as a modern-day lab notebook where you can capture not only what you did, but also what you were thinking.
In Quarto documents, you can use Markdown syntax. You can use this to create bold or italic text (and even text that's both bold and italic), and headers.
Replace the one sentence in quarto-1.qmd
with ## My Header
. Skip a line and add this text.
You can do a lot of cool things in Quarto like **bold** and *italic* text.
Render the file again. Does everything look good in the Viewer?
In the Console, run:
tutorial.helpers::show_file("quarto-1.qmd")
CP/CR.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 6)
You can find a full list of Markdown formatting styles and commands here.
In the top left corner of the Source pane, you should be able to see two buttons: "Source" and "Visual". "Source" shows you all the code while "Visual" shows you (mostly) how the document will look after being rendered. You can edit a Quarto document while in either "Source" or "Visual" mode.
We are going to switch to "Visual" and explore how we can edit while still in "Visual". Switch to "Visual" by clicking on it.
Type I made this through Quarto.
below ## My Header
while still in "Visual" mode. Copy and paste everything in your document except the YAML header --- while still in "Visual" mode --- into the box below.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 5)
Render the document, just to make sure it worked. Note that rendering automatically causes the document to be saved. To encourage the use of shortcut keys going forward, we will start using them directly in our instructions to you. So, instead of writing "Render the document," we will just write Cmd/Ctrl + Shift + K
.
For the most part, we work in "Source" mode because it is easier to see how things work. "Visual" mode is most useful when you are adding images to the document.
If RStudio continues to insert editor: visual
in the YAML header of new documents, you can try to edit the option by hand:
Tools -> Global Options...
to bring up the "Options" box. include_graphics("images/visual-editing-options.jpg")
Restart your R session. (Recall that we do this from the "Session" menu. This is not the same thing as restarting RStudio.) This will require you to Terminate this tutorial. And that is OK! All your work is saved. Just restart the tutorial from the Tutorial tab once your R session restarts.
Let's create another Quarto document so that we can explore how to include R code within the document.
Follow the same procedure as last time to create a new Quarto document. File -> New File -> Quarto Document...
. Use "My Second Quarto Document" as the title and your name for the author. Save the document as quarto-2.qmd
. Cmd/Ctrl + Shift + K
Run list.files()
. CP/CR.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 3)
The listing should include quarto-2.qmd
, quarto-2.html
and the quarto-2_files
directory.
Delete everything in quarto-2.qmd
except for the YAML header. Do not delete the dashes which provide the border for the YAML header. The file should look like this:
--- title: "My Second Quarto Document" author: "Your Name" format: html ---
In the Console, run:
tutorial.helpers::show_file("quarto-2.qmd", end = 6)
CP/CR.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 6)
If you have unchecked the "Editor: Use visual markdown editor" box at the bottom of the "New Quarto Document" box, then the editor: visual
line will not appear in the initial YAML header. If it did appear, delete it.
Add a code chunk either by pressing the Add Chunk command at the top of the Source pane on the right (the green C button with a plus sign next to it) or by using the shortcut key combination: Cmd/Ctrl + Option/Alt + I
. (In other words, on the Mac, the shortcut key is Cmd + Option + I
while on Windows it is Ctrl + Alt + I
.)
The newly created code chunk will be empty, looking like:
Save the file.
In the Console, run:
tutorial.helpers::show_file("quarto-2.qmd")
CP/CR.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 6)
Note the curly braces {}
at the top of the chunk, with an r
inside. The r
indicates that the language which Quarto should use with the code is R.
In this tutorial, we will only include R code within our code chunks. But code chunks can have any programming language in them, from common ones like Python, Java, and C, to esoteric ones like INTERCAL and Whitespace. All you need to do is indicate the language in the curly braces (e.g., {py}
, {ruby}
, etc).
Put 2 * 2
within the code chunk. Cmd/Ctrl + Shift + K
. Copy and paste the entire HTML document, as it appears in the Viewer tab, below. (This allows us to confirm that your HTML file is correct.)
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 8)
We see both the code itself and the result of the code. This is an example of a "reproducible" analysis. We can re-render the document anytime we like, thereby confirming our results.
You can add options to executable code. For example, add #| echo: false
within the code chunk, above the 2 * 2
calculation. It should look like:
Cmd/Ctrl + Shift + K
. Copy/paste the HTML below.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 6)
echo: false
prevents code, but not the results, from appearing in the finished file. Use this when writing reports aimed at people who don’t want to see the underlying R code. Note that this same example appears in the bottom of the default for new Quarto documents.
Code chunk options are always preceded by #|
-- pronounced "hash-pipe". This is followed by an option/value pair, separated by a colon.
Add another code option for this code chunk: #| label: calculation
. You can have multiple code chunk options for a single code chunk. The order does not matter, but each belongs on its own line and must be proceeded by #|
. Cmd/Ctrl + Shift + K
. Copy/paste the HTML below.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 5)
The label
option has no effect on the output. Your chunk labels should be short but evocative and should not contain spaces. We recommend using dashes (-
) to separate words (instead of underscores, _
) and avoiding other special characters in chunk labels.
Delete the current code chunk. Add a new one. In this new code chunk, put library(tidyverse)
. Cmd/Ctrl + Shift + K
. A message about "Attaching core tidyverse packages" should appear in the HTML file. Copy/paste that message below.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 10)
We will include the tidyverse package in almost every Quarto document which we create. Indeed, the top of most Quarto documents includes a code chunk which loads all the packages which we use in the analysis.
Add #| message: false
to the code chunk. Cmd/Ctrl + Shift + K
. Copy/paste the entire HTML file below.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 5)
We want to make our Quarto HTML files beautiful. That means we will almost always "mask" ugly messages like this. Our readers don't care about such aRcana. They care about our analysis.
Add another code chunk option: echo: false
. Don't forget to preface with the hash-pipe: #|
. Cmd/Ctrl + Shift + K
. Copy/paste the HTML below.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 3)
The HTML is empty, except for the title and author.
echo: false
prevents the code from being "echoed," from appearing in the final document. We generally want this because most readers don't know R and don't care about our code.
Add another code chunk option: label: setup
. Don't forget to preface with the hash-pipe: #|
. It is conventional to label the code chunk which loads libraries and takes care of other housekeeping as the "setup" code chunk.
Cmd/Ctrl + Shift + K
. Copy/paste the HTML below.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 3)
You are generally free to label your chunk however you like, but there is one chunk name that imbues special behavior: setup
. When you’re in a notebook mode, the chunk named setup
will be run automatically once, before any other code is run.
Chunk labels cannot be duplicated. Each chunk label must be unique.
Important Point: There are two different "worlds" with which we are dealing. First is the world of the Quarto document, the QMD file. Second is the world of the Console in our current RStudio session. These worlds only connect when we connect them. Something written in a Quarto document --- or an R script --- is not, by default, part of our current R session.
Right now, the tidyverse package has not been loaded into the current R session. To load it, you must run the code chunk. To do so, first place your cursor inside the code chunk. Then, you have multiple options, including:
Cmd/Ctrl + Shift + Enter
will run all the code in the code chunk.
Cmd/Ctrl + Enter
will run just the code at the line in which the cursor is located.
Pressing the small green triangle --- hover to see its name, which is "Run Current Chunk" --- at the upper right of the code chunk will run all the code in the chunk.
Run the code chunk. Run pull(mtcars, 1)
in the Console. CP/CR.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 3)
If you run this command without running library(tidyverse)
in the Console, you will get an error about not finding the "pull" function. The fact that library(tidyverse)
exists in the QMD, and that you have "used" it there by rendering the document, has no bearing on the world of the Console.
Let's create the following scatterplot in our Quarto document:
scat_p <- ggplot(data = iris, mapping = aes(x = Sepal.Width, y = Sepal.Length, color = Species)) + geom_point() + labs(title = "Measurements for Different Species of Iris", subtitle = "Virginica has the longest sepals", x = "Sepal Width", y = "Sepal Length", caption = "Fisher (1936)") scat_p
Create a new code chunk. Add this code.
ggplot(data = iris, mapping = aes(x = Sepal.Width, y = Sepal.Length, color = Species))
Render the file. You should now see your R code (since we did not set echo: false
), as well as a blank plot (since we have not added a geom layer).
In the Console, run:
tutorial.helpers::show_file("quarto-2.qmd", chunk = "Last")
CP/CR.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 10)
Make sure to format your code so that it looks neat and tidy. Specifically:
Put spaces on either side of mathematical operators apart from ^
(i.e. +
, -
, ==
, <
, …), and around the assignment operator (<-
).
Don’t put spaces inside or outside parentheses for regular function calls. Always put a space after a comma, just like in standard English.
|>
should always have a space before it and should typically be the last thing on a line.
If the function you’re piping into has named arguments (like mutate()
or summarize()
), put each argument on a new line. If the function doesn’t have named arguments (like select()
or filter()
), keep everything on one line unless it doesn’t fit, in which case you should put each argument on its own line.
A good resource on neat code is the Tidyverse Style Guide.
To add a geom layer, add geom_point()
to your plot. Render the file again. Now our plot isn't empty! It shows a scatterplot!
In the Console, run:
tutorial.helpers::show_file("quarto-2.qmd", chunk = "Last")
CP/CR.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 10)
RStudio automatically saves the contents of the editor when you quit, and automatically reloads it when you re-open. Nevertheless, it’s a good idea to avoid Untitled1, Untitled2, Untitled3, and so on. Instead, save your documents and give them informative names.
We just built the basic graph, but it still looks a little ugly. Labels are important for adding context to the graph and making it easier to understand.
Use the labs()
function to add appropriate title and axis labels to the graph.
Reminder, this is what our plot should look like:
scat_p
Render the file again to see your completed graph.
In the Console, run:
tutorial.helpers::show_file("quarto-2.qmd", chunk = "Last")
CP/CR.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 2)
We recommend you always start your Quarto documents with the packages you need. That way, if you share your code with others, they can easily see which packages they need to install. Note, however, that you should never include install.packages()
in a Quarto document or R script which you share. It’s inconsiderate to hand off something that will change something on their computer if they’re not being careful!
This section will teach you how to use inline R code, allowing you to insert calculated results in the middle of text.
Create a new Quarto document with "My Third Quarto Document" as the title and you as the author. Save the file as quarto-3.qmd
. Cmd/Ctrl + Shift + K
.
Run list.files()
. CP/CR.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 3)
The files quarto-3.qmd
and quarto-3.html
should appear in this list.
Look at all the default material in the Quarto document. Note the section headers, each defined with two hash hmarks: ##
. This is an example of the markdown syntax which is supported by Quarto.
Copy/paste the last sentence of the HTML file here.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 3)
Remember that variable names (those created by <-
and those created by mutate()
) should use only lowercase letters, numbers, and _
. Use _
to separate words within a name.
As a general rule of thumb, it’s better to prefer long, descriptive names that are easy to understand rather than concise names that are fast to type but hard to understand.
We are now going to learn how to include the results of R calculations inline, that is in the middle of sentence. But, first, delete everything in quarto-3.qmd
after the YAML header. Add a new code chunk. Add x <- 123456789
to that code chunk. Cmd/Ctrl + Shift + K
.
Copy/paste the HTML file below.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 5)
Because we have not added any code chunk options, we see the code in the HTML file, along with the title and author. But there is no output because assignment of a value does not result in printed output in R.
Instead of using the echo: false
code chunk option in every code chunk in a document, we can set this option in the YAML header itself. Add
execute: echo: false
to the bottom of the YAML header. This sets echo
to false
throughout the document. Cmd/Ctrl + Shift + K
. The resulting HTML is empty, other than the title and author.
In the Console, run:
tutorial.helpers::show_file("quarto-3.qmd", start = -5)
CP/CR.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 6)
If we are just using a code option for one or two code chunks, then we can just place them in the relevant code chunks, using the hash-pipe: #|
. However, any code chunk option which applies to most/all code chunks should be placed in the YAML header under the execute:
category.
Be careful of the formatting of the YAML header. It is very fussy! For example, if you forget to indent the echo: false
line, you will get an error.
Below the code chunk, add the following sentence to quarto-3.qmd
: The value of x is ?, a surprisingly high value.
Cmd/Ctrl + Shift + K
.
In the Console, run:
tutorial.helpers::show_file("quarto-3.qmd", start = -6)
CP/CR.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 6)
We want the actual value of x
to appear in the document, in place of the ?
. To do so, we need to make use of inline code.
Replace the ?
in your sentence with:
Include the backticks. They r
tells Quarto that you want to evaluate the code (x
) using the R language. In this case, that code is just the letter x
, which evaluates to (i.e., prints out) the number we have assigned to it. Cmd/Ctrl + Shift + K
.
Copy/paste the resulting HTML.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 3)
This inline code has the desired effect. It "looks up" the value of x
defined in the preceding code chunk. R then prints that value within the sentence, which is what we want.
But, depending on your system and settings, the result is often ugly. I get "1.2345679^{8}", which makes use of scientific notation.
Replace the inline code in your sentence with
Cmd/Ctrl + Shift + K
. Notice that, strictly speaking, you do not need to save the document before you render it. With the usual default settings, RStudio will automatically save a document which you try to render. But it's always a good idea to hit save, just to be on the safe side.
Copy/paste the resulting HTML.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 3)
The comma()
function, which comes from the scales package --- hence our use of the double colon (::
) notation --- causes the value of x
to be formatted nicely.
With inline code, we can insert R code of arbitrary complexity directly in the text of a Quarto document, although it is often better to keep the code itself in a code chunk, assign the final value to a variable like x
and then have a simple piece of inline code, as we do here.
Restart your R session. (Recall that we do this from the "Session" menu. This is not the same thing as restarting RStudio.) This will require you to Terminate this tutorial. And that is OK! All your work is saved. Just restart the tutorial from the Tutorial tab once your R session restarts.
Run search()
in the Console. CP/CR.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 3)
The shortcut key to restart R is Cmd/Ctrl + Shift + 0
. You should restart your R session regularly. Indeed, one of our catch phrases is:
You can't restart R too often.
search()
should not return packages like tidyverse. (However, the default packages like stats and graphics should be there.) This is a new R session, and you have not loaded any non-default packages yet.
Make a new Quarto document. The title is "My Fourth Quarto Document". You are the author. Name the document quarto-4.qmd
, and instead of creating the document as normal, hit "Create Empty Document", in the bottom left corner of the "New Quarto Document" box. Delete the editor: visual
line from the YAML header if necessary.
Save the document as quarto-4.qmd
.
In the Console, run:
tutorial.helpers::show_file("quarto-4.qmd")
CP/CR.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 5)
It might be tempting to name your files code.R
or myscript.R
, but you should think a bit harder before choosing a name for your file. Three important principles for file naming are as follows:
File names should be machine readable: avoid spaces, symbols, and special characters. Don’t rely on case sensitivity to distinguish files.
File names should be human readable: use file names to describe what’s in the file.
File names should play well with default ordering: start file names with numbers so that alphabetical sorting puts them in the order they get used.
We are going to make a setup
code chunk, where you can load your libraries.
Add a new code chunk. In the first line, write #| label: setup
in order to give the code chunk the label/name setup
.
Put library(tidyverse)
and library(knitr)
in the code chunk.
Notice the sloppy language! There are two ways in which we can "load" tidyverse and knitr, corresponding to the two worlds we are working in simultaneous: QMD World and Console World.
Putting the character strings library(tidyverse)
and library(knitr)
inside the setup
code chunk is enough to "load" these packages in QMD World because, whenever we render a file, every line of code in the file is sent to R for processing. Those characters, however, have no connection to Console World until we explicitly execute them by hand, generally with Cmd/Ctrl + Enter
, run once for each line of R code we want executed in the Console.
Do that now. Place the cursor next to the library()
calls and hit Cmd/Ctrl + Enter
twice.
Once all that is done, run search()
in the Console. CP/CR.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 2)
The output of the call to search()
should include the strings package:tidyverse
and package:knitr
, indicating that both tidyverse and knitr are loaded.
The key lesson is that we are operating in two worlds simultaneously: QMD World and Console World. We are responsible for keeping them in sync with tools like Cmd/Ctrl + Enter
.
Our HTML file looks ugly, both because of the annoying message and because it shows the R code. We want neither. Add echo: false
and message: false
to the code chunk options. Cmd/Ctrl + Shift + K
.
In the Console, run:
tutorial.helpers::show_file("quarto-4.qmd", chunk = "Last")
CP/CR.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 5)
There is a great pair of keyboard shortcuts that will work together to make sure you’ve captured the important parts of your code in the editor:
Cmd/Ctrl + Shift + 0
to restart R.Cmd/Ctrl + Shift + K
to re-render the current Quarto document.We collectively use this pattern hundreds of times a week.
Alternatively, if you don’t use keyboard shortcuts, you can go to Session > Restart R
and then press the "Render" button.
Make a new header with the title "Diamonds Histogram". Remember we do this using ##
, followed by a space. Skip a line under this header, and then create a new code chunk. Use the code chunk option echo: false
to stop your code from showing up when you render the file.
In your new code chunk, use the function knitr::include_graphics()
. Set the argument to the name of your PNG. Remember to use quotes. The command should look like
knitr::include_graphics("diamonds.png")
Cmd/Ctrl + Shift + K
.
In the Console, run:
tutorial.helpers::show_file("quarto-4.qmd", chunk = "Last")
CP/CR.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 3)
This should cause the graphic to appear in the HTML file. If you get an error, make sure that you have a file called diamonds.png
in your working directory.
We'll be publishing our Quarto documents on the web by using RPubs, a free web publishing service. RPubs is managed by Posit (formerly RStudio), a leading company in the data science world. You will need to create a free account. Do not give them your credit card number.
Register for a free RPubs account. When choosing a user name, follow this advice.
Write down the main URL for your account. It should look something like:
https://rpubs.com/dkane
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 3)
There are other free (and paid) services for publishing on the web. We make use of Quarto Pub in other tutorials in this package.
Render the quarto-4.qmd
file. By rendering, you are generating an HTML file, which is what is actually published on the web.
Run list.files()
in the Console. CP/CR.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 2)
You should see a quarto-4.html
file, which was generated after you rendered your QMD. (Note that the "qmd" file extension stands for Quarto Markdown Document.)
We sometimes edit the YAML header to get rid of information like the date and title, as it sometimes looks bad in the final render. However, make sure not to mess with the rest of the YAML formatting because it is a very structurally sensitive language. You can learn more about YAML editing at bookdown.org.
Notice a blue icon in the upper right-hand corner of your Quarto document. It should look like the image below.
include_graphics("images/publish_button.png")
Press that button.
You will be asked whether you want to publish to RPubs or to Posit Connect. Use RPubs. (Posit Connect costs money.) You will get a reminder that all documents you publish on RPubs are publicly visible. Click "Publish".
include_graphics("images/rpubs-6.png")
This will take you to the RPubs website. You may need to sign into your account.
Add document details. Name your document. Add a meaningful slug (a unique website name that's often just the name of your project), otherwise you will end up with an ugly, long address you didn't choose and can't remember. You can leave the description blank if you don't want to add one.
Put the link to your new RPubs page in the space below.
question_text(NULL, answer(NULL, correct = TRUE), allow_retry = TRUE, try_again_button = "Edit Answer", incorrect = NULL, rows = 2)
Keep in mind that this is now a website that can be found on the internet, for anyone to see.
This tutorial covered Chapter 2 Workflow: basics, Chapter 4 Workflow: code style, Chapter 6 Workflow: scripts and projects, and some material in Chapter 28 Quarto from R for Data Science (2e) by Hadley Wickham, Mine Çetinkaya-Rundel, and Garrett Grolemund. You learned how to create Quarto documents and how to publish your work to the web using Rpubs.
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.