Introduction
R Markdown lets you combine code, output, and text
in the same document. You can write your analysis, include plots, and
explain your results — all in one file — and render it into an HTML,
PDF, or Word report.
This guide will help you:
- Understand the basic structure of an
.Rmd
file
- Write text using Markdown formatting
- Add and run R code chunks
- Render the document to HTML
R Markdown Structure
An R Markdown file has three parts:
- YAML header – appears at the top between
---
lines (title, author, etc.)
- Markdown text – regular writing with
formatting
- Code chunks – blocks of R code surrounded by three
backticks
Writing Text with Markdown
You can write italic, bold, and even
lists:
You can also add links:
[Visit RStudio's R Markdown site](https://rmarkdown.rstudio.com)
Visit RStudio’s R Markdown
site
And equations:
`$E = mc^2$` → \(E = mc^2\)
$E = mc^2$
→ \(E =
mc^2\)
Code Chunks
To include R code, use a
code chunk using this syntax:
```{r} x <- 5 x + 10 ```
Ends up looking like this:
# A simple calculation
x <- 5
y <- 10
x + y
## [1] 15
Adding Plots
Plots can be added using the same ‘chunk’ syntax:
# Make a simple scatterplot
plot(mtcars$mpg, mtcars$wt,
xlab = "Miles per Gallon",
ylab = "Weight",
main = "Car Weight vs MPG")

Chunk Options
You can control what appears in your report with chunk options in with
the {r} curly braces: e.g.,
```{r, echo=FALSE, eval=FALSE} x <- 5 x + 10 ```
:
- echo=FALSE → hide code, show results
- eval=FALSE → show code, but don’t run it
- message=FALSE, warning=FALSE → hide messages/warnings
Rendering Your Document
Click Knit in RStudio and choose Knit to HTML.
R will:
- Run all the code chunks
- Combine them with your text
- Produce a clean, shareable report
Tips for Success:
- Save your .Rmd file often.
- Knit regularly to catch errors early.
- Use clear headings (#, ##, ###) to organize your report.
- Keep code readable: use comments (#) to explain what it does.
- Load the libraries you need at the beginning of the document. Don’t
try to use an object you haven’t defined earlier in the document. Rmd
runs the R code from the beginning of the file to the end, so if the
library or object haven’t been defined, the Rmd file won’t run.
- Don’t install.packages or use
View(data)
in Rmd
files.
Practice
Try using the mtcars
dataset and adding:
- A summary statistic, mean of disp
- A histogram of disp
- A short paragraph explaining what you found
- Then knit again and see how your document updates!