Code
Example R code chunk
5+5
[1] 10
In RStudio, you can create a new R Markdown file via the menu: File -> New File -> R Markdown...
. This opens a dialog where you can choose the output format and other options.
R Markdown supports standard Markdown syntax. Here are some basic examples:
#
for headers. E.g., # Header 1
, ## Header 2
.**bold**
for bold text and *italic*
for italic text.-
or *
for unordered lists and numbers for ordered lists.[link text](URL)
to create hyperlinks.
to insert images.You can embed R code within your document by using the following syntax:
Example R code chunk
5+5
[1] 10
The {r}
indicates that this is an R code chunk. The code inside this chunk is executed, and its results are included in the document below the chunk.
To compile the document into your desired output format, click the “Knit” button in RStudio. This will execute all R code within the document and render it to the specified output format.
Dynamic Report Generation
Multiple Output Formats
Reproducibility
Ease of Use
Here’s a simple example of an R Markdown document that performs a basic data analysis:
Min. 1st Qu. Median Mean 3rd Qu. Max.
4.0 12.0 15.0 15.4 19.0 25.0
Let’s calculate summary statistics for the pressure
dataset:
temperature pressure
Min. : 0 Min. : 0.0002
1st Qu.: 90 1st Qu.: 0.1800
Median :180 Median : 8.8000
Mean :180 Mean :124.3367
3rd Qu.:270 3rd Qu.:126.5000
Max. :360 Max. :806.0000
You can also embed plots. For example, here’s a plot of pressure vs temperature:
options(repos = c(CRAN = "https://cran.rstudio.com/"))
knitr::opts_chunk$set(message = FALSE)
The most important set of options controls if your code block is executed and what results are inserted in the finished report:
eval = FALSE prevents code from being evaluated. (And obviously if the code is not run, no results will be generated). This is useful for displaying example code, or for disabling a large block of code without commenting each line.
include = FALSE runs the code, but doesn’t show the code or results in the final document. Use this for setup code that you don’t want cluttering your report.
echo = FALSE prevents code, but not the results from appearing in the finished file. Use this when writing reports aimed at people who don’t want to see the underlying R code.
message = FALSE or warning = FALSE prevents messages or warnings from appearing in the finished file.
error = TRUE causes the render to continue even if code returns an error.
Option | Run code | Show code | Output | Plots | Messages | Warnings |
---|---|---|---|---|---|---|
eval = FALSE |
||||||
include = FALSE |
✓ | |||||
echo = FALSE |
✓ | ✓ | ✓ | ✓ | ✓ | |
results = "hide" |
✓ | ✓ | ✓ | ✓ | ✓ | |
fig.show = "hide" |
✓ | ✓ | ✓ | ✓ | ✓ | |
message = FALSE |
✓ | ✓ | ✓ | ✓ | ✓ | |
warning = FALSE |
✓ | ✓ | ✓ | ✓ | ✓ |