A traditional way to work in RStudio
is to have a script
window on one side and the console on the other. The console operates
like a terminal, where you can enter commands and see immediate text
output.
Comments in R are preceded by a #
sign. Anything after
the #
on the same line is ignored by the R interpreter.
Two useful tricks for working in the console:
The paradigm we will be using in this course minimizes direct use of the console, as we will be working primarily within R Markdown files, where we can integrate notes, code, and output in a single, organized document.
This file is an R Markdown document, a powerful tool for creating
dynamic, reproducible reports. Think of it as a notebook where you can
seamlessly blend narrative text, R code, and the output of that code. R
Markdown files, which have the .Rmd
extension, are
essential for modern data analysis and reporting.
With R Markdown, you can author a single file and render it in various formats, including:
Note on Quarto: An even more advanced tool called Quarto is available. It extends R Markdown’s capabilities and supports Python, Julia, and Observable in addition to R. While we won’t use Quarto in this course, it’s a valuable tool to be aware of for your future work.
For more resources, see the official R Markdown website: rmarkdown.rstudio.com. For a
quick reference guide, go to
File > Help > Markdown Quick Reference
. For a
comprehensive cheat sheet, see
File > Help > Cheat Sheets > R Markdown Cheat Sheet
.
The definitive guide is the free online book R Markdown: The
Definitive Guide by Yihui Xie, J. J. Allaire, and Garrett
Grolemund, available at bookdown.org/yihui/rmarkdown.
R Markdown provides a seamless way to integrate text, code, and results, ensuring that your analysis is transparent and reproducible. It is highly flexible, allowing you to produce different types of documents (reports, presentations, websites) from the same source file. This versatility makes it a popular choice among researchers and data analysts. Using R Markdown ensures that your work is easily shareable and that others can replicate your analysis without difficulty.
To create a new R Markdown document in RStudio:
File -> New File -> R Markdown
.OK
to generate a new R Markdown file with some
example content.Knit
button to render the document into the
desired output format.An R Markdown document has three main components. The
header, which is enclosed in triple-dashed lines
(---
), contains metadata about the document, such as the
title, author, and output format. The body of the document is composed
of text and Markdown, where you can write your
narrative and apply formatting, and code chunks, which
are blocks of R code that can be executed when the document is
rendered.
R Markdown uses Markdown, a lightweight markup language with a
plain-text formatting syntax. You can create headings using
#
for a level-one header, ##
for a level-two
header, and so on. To make text bold, enclose it in
**
or __
; for italics, use
*
or _
. You can create unordered lists with
-
or *
, and ordered lists with numbers. Links
are created with the syntax [Link Text](URL)
, and images
with 
.
A code chunk is a specially delimited section of your R
Markdown file where you can embed R code. To insert a code chunk, you
can go to Code > Insert Chunk
in the RStudio menu, click
the +C
button in the editor toolbar, or use the keyboard
shortcut Ctrl+Alt+I
(Windows/Linux) or
Cmd+Option+I
(macOS).
Code chunks begin with three backticks and {r}
and end
with three backticks. You write your R code inside the chunk, and your
narrative text outside of it.
You can control the behavior of code chunks with various options. For
example, including echo=FALSE
in the chunk header will hide
the code but display the output, while eval=FALSE
will show
the code but prevent it from being executed.
## [1] "2025-08-04"
Sys.Date()
A common practice at the beginning of an R Markdown document is to have a setup chunk. This chunk is used to define global options for your document and to load any necessary libraries.
The first part of the chunk header, r
, is mandatory and
specifies the language. The second part, setup
, is a unique
label for the chunk, which is good practice for organization and
debugging. The include=FALSE
option ensures that the code
in this chunk is executed but not displayed in the final document.
It’s crucial to load all required libraries at the beginning of your
document. If a library is not loaded, R will be unable to find the
functions it contains, resulting in errors. For now, we are only using
the gapminder
package.
When you execute a code chunk, the output is displayed directly below
it. For example, the head()
function displays the first few
rows of a dataset. By default, it shows the first six, but we can change
that with the n=
argument. Notice how the output is neatly
formatted, unlike the plain text output in the console.
gapminder
## # A tibble: 1,704 × 6
## country continent year lifeExp pop gdpPercap
## <fct> <fct> <int> <dbl> <int> <dbl>
## 1 Afghanistan Asia 1952 28.8 8425333 779.
## 2 Afghanistan Asia 1957 30.3 9240934 821.
## 3 Afghanistan Asia 1962 32.0 10267083 853.
## 4 Afghanistan Asia 1967 34.0 11537966 836.
## 5 Afghanistan Asia 1972 36.1 13079460 740.
## 6 Afghanistan Asia 1977 38.4 14880372 786.
## 7 Afghanistan Asia 1982 39.9 12881816 978.
## 8 Afghanistan Asia 1987 40.8 13867957 852.
## 9 Afghanistan Asia 1992 41.7 16317921 649.
## 10 Afghanistan Asia 1997 41.8 22227415 635.
## # ℹ 1,694 more rows
R Markdown helps us to dynamically create our documents with all of our data available. For example, there are 1704 observations. When the data changes, the document updates automatically. This avoids having you hunt and peck through your document as you manually update results like a barbarian.
When you click the Knit button, a document is generated that includes both content and the output of any embedded R code chunks within the document. You can knit to HTML or PDF.
Try knitting this document now by clicking the “Knit” button in the RStudio toolbar, or choosing File > Knit Document from the RStudio menu.
Now that we have an HTML file, we can publish it to the web with a few clicks using RPubs. You’ll need to create a free account on the RPubs website first. How cool is that?
Let’s try knitting to a PDF, too. Notice the fonts change to a serif font (specifically, Computer Modern, written by Don Knuth in the 1980s!) more appropriate for the printed page.
Now let’s explore some other parts of the RStudio interface.
Let’s start with the Global Options. Click on the “Tools” menu, then “Global Options”. You can change the appearance of RStudio, the default working directory, and many other settings here.
While most of the default settings are fine, let’s make some quick changes that I think will give you a better time.
The RStudio toolbar provides buttons for common tasks such as saving, opening files, and knitting documents. Many tasks can also be performed using keyboard shortcuts, which are useful for speeding up your workflow.
RStudio provides two modes for editing R Markdown documents: source mode and visual mode.
Source Mode: This is the default mode where you write R Markdown code directly. It offers full control over the document’s content and structure.
Visual Mode: RStudio’s visual mode was introduced in 2021. It offers a Word processor-like WYSIWYG (What You See Is What You Get) interface for editing R Markdown documents, making it easier for users to format text, insert footnotes1, add images, and insert tables without needing to write raw Markdown syntax. This mode allows users to switch between source mode, where they can edit the raw R Markdown code, and visual mode, where they can see a live preview of the formatted document as they make changes. Visual mode streamlines the document creation process, particularly for those who are more comfortable with graphical interfaces, ensuring that the final output looks polished and professional with minimal effort. This is a useful tool, but you should be comfortable working in both interfaces.
Visual mode supports both traditional keyboard shortcuts
(e.g., Ctrl+B
for bold and Ctrl+I
for italic)
as well as markdown shortcuts. For example, you can type ##
followed by a space to create a second-level heading, or select text and
press Ctrl+K
to transform it into a hyperlink.
Use the forward slash (“/”) to insert many common items like lists, code chunks, and more.
Click the outline button on the top right of the RStudio window to
get a hierarchical overview of the current R Markdown document. This
feature helps you quickly navigate to different sections of your
document. Alternatively, you can use the section selector button at the
bottom middle of the RStudio
interface to jump to specific
sections.
In the console and the source panes, RStudio provides code completion and function help. Here are some examples:
head(
and then press Tab
,
RStudio will show you the arguments for the head()
function.hea
, RStudio will suggest a number of
commands that begin with hea
, including
head()
.gapminder$
and then press Tab
,
RStudio will show you the columns in the gapminder
dataset.gapminder
, one of the options will show a
preview of the whole dataset.gapminder
## # A tibble: 1,704 × 6
## country continent year lifeExp pop gdpPercap
## <fct> <fct> <int> <dbl> <int> <dbl>
## 1 Afghanistan Asia 1952 28.8 8425333 779.
## 2 Afghanistan Asia 1957 30.3 9240934 821.
## 3 Afghanistan Asia 1962 32.0 10267083 853.
## 4 Afghanistan Asia 1967 34.0 11537966 836.
## 5 Afghanistan Asia 1972 36.1 13079460 740.
## 6 Afghanistan Asia 1977 38.4 14880372 786.
## 7 Afghanistan Asia 1982 39.9 12881816 978.
## 8 Afghanistan Asia 1987 40.8 13867957 852.
## 9 Afghanistan Asia 1992 41.7 16317921 649.
## 10 Afghanistan Asia 1997 41.8 22227415 635.
## # ℹ 1,694 more rows
If you have a valid license, you can use the Copilot feature in RStudio. This feature provides code suggestions and completions based on the context of your code. To enable Copilot, go to Tools -> Global Options -> Code -> Copilot and check the box.
You can then use the Tab
key to accept a suggestion or
the Esc
key to dismiss it. There is sometimes a conflict
between the Copilot and the RStudio code completion feature, so you need
to be careful here.
Like this one.↩︎