01 / 22
R

R Markdown
Reproducible Reports

Learn how to combine R code, narrative text, and output in a single document that anyone can reproduce and verify.

R Programming

What Is R Markdown?

R Markdown is an authoring framework that lets you write a single .Rmd file containing prose, code, and results. When you render ("knit") the file, R executes every code chunk and weaves the output into a polished document.

Text
Markdown-formatted narrative: headings, bold, italic, lists, links
Code
R (or Python, SQL) chunks that run during rendering and produce output
Output
Tables, plots, and computed values embedded directly in your report

Why Reproducibility Matters

Traditional workflows separate analysis (code) from reporting (Word, slides). When data changes, you manually copy-paste updated numbers: a recipe for errors and inconsistency. R Markdown solves this by keeping everything in one place.

The Three Layers of an .Rmd File

YAML Header title, author, date, output format Markdown Text # Headings, **bold**, *italic*, bullet lists Narrative paragraphs explaining your analysis Code Chunks ```{r chunk_name} summary(data) # R code that executes ```

The YAML Header

YAML ("Yet Another Markup Language") sits between triple dashes --- at the very top of your file. It controls metadata and output settings.

--- title: "My Analysis Report" author: "Jane Doe" date: "2025-01-15" output: html_document ---

Markdown Syntax Essentials

Between code chunks, you write in Markdown: a lightweight formatting language. Here are the most common elements:

Syntax Result
# Heading 1Top-level heading
## Heading 2Section heading
**bold text**bold text
*italic text*italic text
- itemBullet list item
[text](url)Hyperlink
![alt](img.png)Image embed

Code Chunks: The Engine

Code chunks are fenced with triple backticks and a language specifier. They are the executable heart of your document.

```{r summary_stats, echo=TRUE} # Load data and compute mean library(dplyr) avg_score <- mtcars %>% summarize(mean_mpg = mean(mpg)) avg_score ```
Chunk Name
Optional label after {r for navigation and caching
Chunk Options
Key-value pairs like echo, eval, message that control behavior

Key Chunk Options

1
echo = TRUE/FALSE: Show or hide the source code in the output document
2
eval = TRUE/FALSE: Actually run the code (TRUE) or display it without executing (FALSE)
3
message = FALSE: Suppress package loading messages that clutter the report
4
warning = FALSE: Suppress warning messages from appearing in output
5
fig.width / fig.height: Control the dimensions of plot output (in inches)

.R Script vs .Rmd File

.R Script .Rmd File
Purpose Pure code execution Code + narrative report
Text support Comments only (#) Full Markdown formatting
Output Console/plots only HTML, PDF, Word, slides
Reproducibility Requires separate docs Self-contained document
Sharing Send code + report separately One file produces everything

The Knit Pipeline

.Rmd Your file knitr Runs R code .md Markdown Pandoc HTML PDF Word Slides

Creating Your First Report

1
Open RStudio and go to File → New File → R Markdown
2
Fill in the dialog: enter title, author, and choose output format (HTML is a great start)
3
Edit the YAML header between the --- delimiters to customize metadata
4
Write Markdown text to explain your analysis: use headings, bold, and lists
5
Insert code chunks with Ctrl+Alt+I (or Cmd+Option+I on Mac) and write R code inside
6
Click "Knit" (or press Ctrl+Shift+K) to render your final document

Inline Code: Dynamic Values

Beyond code chunks, you can embed single computed values directly into your narrative text using inline R code. This ensures numbers in your prose always match your data.

The average fuel efficiency is `r mean(mtcars$mpg)` miles per gallon.

Example 1: Basic Data Summary

--- title: "Cars Report" output: html_document --- ## Overview This report summarizes the **mtcars** dataset. ```{r summary, echo=FALSE} summary(mtcars[, 1:3]) ``` The dataset contains `r nrow(mtcars)` observations.

Example 2: Embedding a Plot

```{r scatter_plot, fig.width=6, fig.height=4} library(ggplot2) ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point(color = "steelblue") + labs( title = "Weight vs. Fuel Efficiency", x = "Weight (1000 lbs)", y = "Miles per Gallon" ) ```

Example 3: Formatted Tables

```{r nice_table, echo=TRUE, message=FALSE} library(knitr) top_cars <- mtcars[1:5, c("mpg", "cyl", "hp")] kable(top_cars, caption = "Top 5 Cars") ```

Common Mistakes

✕ Missing --- delimiters
Forgetting the closing --- after the YAML header causes the entire document to fail to render.
✕ Wrong backtick count
Code chunks need exactly three backticks (```). Using two or four breaks the chunk boundary.
✕ Hardcoding values
Typing numbers manually instead of using inline `r expr` defeats the purpose of reproducibility.

Summary: R Markdown at a Glance

Concept What It Does Key Syntax
YAML Header Sets metadata and output format --- title: "..." ---
Markdown Formats narrative text # heading, **bold**
Code Chunks Executes R code ```{r} ... ```
Inline Code Embeds computed values `r expression`
Chunk Options Controls chunk behavior echo, eval, fig.width
Knit Renders final document Ctrl+Shift+K

Question 1 of 5

What are the three main layers of an R Markdown (.Rmd) file?

Question 2 of 5

What does the chunk option echo = FALSE do?

Question 3 of 5

Which tool in the knitting pipeline is responsible for converting .md into HTML or PDF?

Question 4 of 5

How do you embed a computed value directly inside a sentence in R Markdown?

Question 5 of 5

Which of the following is NOT a valid output format specified in the YAML header?