Code
```{r}
# Below is code written in R.
print("Hello from the R Interpreter!")
= 7
x
x```
[1] "Hello from the R Interpreter!"
[1] 7
Quarto and it’s predecessor, R Markdown, hold code, output, tables, graphs, descriptions, interpretations, and more in a single document. While Quarto files contain R code, they can render into aesthetic, easily shared documents like pdf and html, that show as little or as much R code and output as desired. Many R textbooks, including Data Essentials With R, were written entirely with Quarto or R Markdown files. R for Data Science and Advanced R are other examples.
New Quarto files are formatted with three parts:
YAML header
Markdown space
Code chunks
YAML headers consist of key: value pairs that control how Quarto files render or “knit” into a polished document. YAML headers determine if the Quarto file renders into a webpage (.html), flat file (.pdf), MS Word document (.docx), or other file types. Also, YAML can be added to individual code chunks to customize the appearance of code and output from those code chunks when rendering. RStudio creates YAML headers automatically when opening new Quarto files. Modifications are generally not necessary but intuitive to implement when desired.
The white background of a Quarto file is for writing in R Markdown. In R Markdown, content and formatting commands are intermixed in the script. When the document renders though, formatting commands are executed and hidden from view.
R Markdown is one of many variations (more like a dialect) of the Markdown language. With R Markdown, we can generally write in plain English, because the formatting commands use special characters like \, $, *, [], and {}.
RStudio contains buttons (top left) to switch between a visual editor and a source editor. The visual editor hides Markdown formatting commands, shows the text content in a semi-polished appearance, and provides buttons for the most common formatting tasks, such as bold, italics, and underline.
Code chunks interrupt the markdown space with areas for writing code. New Quarto files come pre-formatted with code chunks that demonstrate the functionality of Quarto files and the R language.
Code chunks begin and end with three backtick marks. These backticks tell RStudio to stop reading R Markdown and start reading the programming language specified inside curly braces. Here is an example:
```{r}
# Below is code written in R.
print("Hello from the R Interpreter!")
= 7
x
x```
[1] "Hello from the R Interpreter!"
[1] 7
Code chunks organize an analysis into sections analogous to paragraphs of an essay. We add code chunks by one of several methods:
Key shortcut: Press “option + command + i”
Click the green and white +C icon above the editor pane.
From the Insert pull-down menu above the visual editor pane, select “Code Chunk” and choose the programming language you wish to use.
Open a new quarto file. Add a new code chunk using the key shortcut method. Type plot(x = -5:5, y = x^2)
on a blank line of code inside the chunk. With the cursor anywhere on this line of code press “command/control +”Enter”. Lastly, click “Render” above the editor pane and choose “Render HTML”.
After opening a new quarto file, delete everything after the YAML header. With the cursor on a line below the YAML header, press “command + option + i” to insert a code chunk. Add R commands inside the code chunks and provide explanations in the Markdown space between code chunks.
R users worldwide create and donate software packages that extend R’s utility. R packages must be installed on personal computers before use, just like any other software. Packages are installed using the “Packages” menu in the bottom right panel of RStudio, or by executing install.packages("package_name")
in the R console. Do NOT include the install.packages()
command inside a code chunk.
Installed packages must be loaded in a Quarto document before use.
Newer versions of RStudio often detect packages that are needed but not installed. RStudio produces a message related to the uninstalled packages and provides an install option if the packages are available in online repositories.
Loading packages is performed with the library() command, as shown below. Before writing other code, we often load staple packages like tidyverse() and knitr(). The tidyverse package contains features for importing, modifying, and summarizing tibbles and dataframes. Knitr is a package that provides tools for rendering documents. KableExtra is a package that produces tables formatted for presentation or publication.
library(knitr)
library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr 1.1.4 ✔ readr 2.1.5
✔ forcats 1.0.0 ✔ stringr 1.5.1
✔ ggplot2 3.5.1 ✔ tibble 3.2.1
✔ lubridate 1.9.3 ✔ tidyr 1.3.1
✔ purrr 1.0.2
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag() masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(kableExtra)
Attaching package: 'kableExtra'
The following object is masked from 'package:dplyr':
group_rows
Notice from the output that when a package is first loaded, R indicates the load was successful and identifies new commands that override or “mask” existing commands from base R or other packages.
The p_load command from the pacman package can load multiple packages simultaneously. Also, add #| warning: false
to the top of a code chunk to avoid showing unimportant messages and warnings in the rendered document. Alternatively, add #| echo: false
, and both the code and output will disappear from the rendered document.
```{r}
#| warning: false
::p_load(knitr, tidyverse, kableExtra)
pacman```
With RStudio’s visual editor, learning R Markdown is not necessary. The visual editor provides formatting buttons and hides the formatting characters intermixed with content. However, switching to the source editor reveals the formatting characters, which are generally easy to interpret and modify.
Think of a Quarto file as an instruction manual or text book with big units indicated by a single hashtag, chapters by two hashtags, chapter subsections by three hashtags, etc.
See the online Quarto Markdown Basics documentation.
From the visual editor, the “Render” pull-down menu provides options to produce the polished document as a .html, .pdf, or .docx file. Select one of these options now. If the render fails, read the error messages and try to fix the problem. Often this means installing additional packages called dependencies.