Console

The old-fashioned way to work in RStudio is to have a script window on the right and the console window on the left. The console operates like a terminal, with text commands given as input and text output immediately below.

Comments in the console are preceded by a # sign. You can have them anywhere in the line, but they are ignored by R.

Two tricks here:

The alternative paradigm we are working with minimizes the need for a console since notes, code, and output are all entered in the journal/script window.

What is R Markdown?

This is an R Markdown file. Think of it as a code notebook where you can take notes, write code, and produce a reproducible document that records your work. R Markdown is a file format for making dynamic documents with R. It allows you to combine code, results, and narrative in a single document, making it an essential tool for reproducible research and dynamic reporting. R Markdown files have the extension .Rmd. R Markdown is useful for working with code and text in RStudio. But more than that, it is used to author various output formats, including:

NB: There is a more advanced version of R Markdown called Quarto, but we will not be using it in this course.

For more details on using R Markdown, see http://R Markdown.rstudio.com. For a quick reference, click File -> Help -> Markdown Quick Reference. For a PDF cheat sheet, click File -> Help -> Cheat Sheets -> R Markdown Cheat Sheet. For the best free book on Markdown called R Markdown: The Definitive Guide by Yihui Xie, J. J. Allaire, and Garrett Grolemund, see https://bookdown.org/yihui/R Markdown/.

Why Use R Markdown?

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.

Creating R Markdown Documents

To create a new R Markdown document in RStudio:

  1. Click on File -> New File -> R Markdown.
  2. Choose a title and author, then select a document type (HTML, PDF, or Word).
  3. Click OK to generate a new R Markdown file with some example content.
  4. Replace the example content with your own text, code, and results.
  5. Use the Knit button to render the document into the desired output format.

The Elements of R Markdown

An R Markdown document consists of three main components:

  1. Header: Contains metadata about the document such as title, author, and output format. The metadata is delimited by three dashes at the start and end. For now, all we are specifying are the title, author, date, and output format(s).
  2. Text and Markdown: Narrative text and formatting using Markdown syntax.
  3. Code Chunks: Blocks of code that can be executed within the document.

Formatting

R Markdown is based on Markdown which is first and foremost a lightweight markup language with plain text formatting syntax. Here are some basic elements you should already see me using in this document:

Code Chunks

A code chunk is a specially delimited section of the file and allow you to embed R code in your R Markdown document. You can add one by moving the cursor to a blank line and choosing Code > Insert Chunk from the RStudio menu, clicking the +C button at the top right of the editor window, or pressing CTRL-I (on Windows/Linux) or CMD-Option-I (on Mac). An empty chunk will appear:

Code chunks are delimited by three backticks (found to the left of the 1 key on US and UK keyboards) at the start and end. Each chunk starts with three backticks followed by {r} to indicate the R language, and ends with three backticks. Write your code inside the code chunks. Write your notes and other material around them, as shown here.

You can control the behavior and appearance of code chunks using chunk options. For example, echo=FALSE will hide the code but show the output, and eval=FALSE will prevent the code from being executed.

## [1] "2025-04-29"
Sys.Date()

Knitting Documents

When you click the Knit button (the icon at the top of the RStudio window that looks like a ball of thread and needle), a document is generated that includes both content and the output of any embedded R code chunks within the document.

Set Up Your Project and Load Libraries

Let’s go deeper into a typical way we’d begin an R Markdown document.

To begin, we set up some options. Notice that the braces at the start of the code chunk have additional options. The language r is required. The setup is a label for your code chunk. Labels are useful for briefly describing what the chunk does. Label names must be unique (no two chunks in the same document can have the same label) and cannot contain spaces. After the comma, the option include=FALSE is set, which tells R to run this code but not include the output in the final document.

Then we must load some libraries we will be using. If we do not load them, R will not be able to find the functions contained in these libraries. Currently, we’re just using the gapminder package.

Output

If we execute code inside a chunk, we get output right below the chunk. For example, here is the output of the head() function applied to the gapminder dataset.

head(gapminder,n=20)
## # A tibble: 20 × 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.
## 11 Afghanistan Asia       2002    42.1 25268405      727.
## 12 Afghanistan Asia       2007    43.8 31889923      975.
## 13 Albania     Europe     1952    55.2  1282697     1601.
## 14 Albania     Europe     1957    59.3  1476505     1942.
## 15 Albania     Europe     1962    64.8  1728137     2313.
## 16 Albania     Europe     1967    66.2  1984060     2760.
## 17 Albania     Europe     1972    67.7  2263554     3313.
## 18 Albania     Europe     1977    68.9  2509048     3533.
## 19 Albania     Europe     1982    70.4  2780097     3631.
## 20 Albania     Europe     1987    72    3075321     3739.

Knitting

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. 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.

Exploring RStudio

Now let’s explore some other parts of the RStudio interface.

Global Options

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.

  • General
    • Make sure Restore .RData into workspace at startup is unchecked
    • Make sure Save workspace to .RData on exit is unchecked
  • Code
    • Make sure “Use Rainbow Parentheses” is checked under “Display”
    • Make sure “Use Native Pipe Operator” is checked under “Editiing”
  • Appearance
    • Change fonts to your liking
  • Pane Layout
    • Change the layout to your liking. My preference is for the console to be on the bottom left, the environment/history to be on the top left, the source to be on the top right, and the files/plots/packages/help to be on the bottom right.
  • R Markdown
    • Show output preview in “Viewer Pane”
  • Sweave
    • Make sure “Preview PDF” is set to “Use RStudio Viewer”

Toolbar and Shortcuts

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. For example, you can use Ctrl + B for bold text or Ctrl + I for italic text. Additionally, you can create headers by typing # followed by a space for a first-level header, ## for a second-level header, and so on.

Source Mode and Visual Mode

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.

There are keyboard shortcuts for all basic editing tasks which are already available in the toolbar. Visual mode supports both traditional keyboard shortcuts (e.g. ^B for bold or ^I for Italic) as well as markdown shortcuts (using markdown syntax directly). For example, enclose Bold text in asterisks or press CTRL-B to make something bold. Or type ## and press space to create a second level heading. Or select some 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.

Outline and Sections

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.

Environment and History

  • Environment: Click on this tab in the Environment/History pane to see which objects are in memory and what they are.
  • History: Click on this tab in the Environment/History pane to see a history of every command or pipeline you ran in R.

  1. Like this one.↩︎