In R Markdown, we can control how code, output, and graphics appear
in our knitted documents by specifying chunk options
inside the {r} header.
| Option | Default | What it does |
|---|---|---|
eval |
TRUE |
If FALSE, the code is displayed but not executed. |
echo |
TRUE |
If FALSE, the code is executed but not displayed. |
message |
TRUE |
If FALSE, messages from R are hidden in the knitted
document. |
warning |
TRUE |
If FALSE, warning messages are hidden in the knitted
document. |
For example:
```{r, echo=FALSE, message=FALSE, warning=FALSE}
summary(cars)
```
This runs the code and displays its output, but hides the R code itself, along with any messages or warnings.
Note: echo=FALSE does not prevent code
from running. eval=FALSE does.
| Option | Default | What it does |
|---|---|---|
fig.align |
"left" |
Controls alignment of the figure ("left",
"center", "right"). |
fig.height |
7 |
Controls the height of the generated figure in inches. |
fig.width |
7 |
Controls the width of the generated figure in inches. |
out.height |
Automatic | Controls the displayed height of the figure in the knitted document. |
out.width |
Automatic | Controls the displayed width of the figure in the knitted document. |
For example:
```{r, fig.align="center", fig.height=5, fig.width=7, out.width="80%"}
hist(rnorm(1000))
```
This generates a figure that is 7 inches wide and 5 inches tall, centers it, and displays it at 80% of the available document width.
The distinction between
fig.width/fig.height and
out.width/out.height is sometimes important:
fig options control the dimensions of the figure when R
creates it, while out options control how large that figure
appears in the final document. Resizing with out.width does
not change the underlying plot layout.
You can specify output dimensions using values such as
out.width="75%", out.width="5in", or
out.height="3in", depending on the output format.
Rather than specifying the same options in every code chunk, we can
set default chunk options in the setup chunk at the beginning
of our R Markdown document. We do this using
knitr::opts_chunk$set().
For example, the following setup chunk hides warnings and messages throughout the document:
```{r setup, include=FALSE}
knitr::opts_chunk$set(
echo = TRUE,
warning = FALSE,
message = FALSE,
fig.align = "center",
fig.width = 7,
fig.height = 5
)
```
These settings apply to all subsequent code chunks unless we specify
something different in an individual chunk. For example, we could use
echo=FALSE in a particular chunk to hide its code while
leaving the default settings unchanged.
The option include=FALSE in the setup chunk means that
neither the setup code nor its output will appear in the knitted
document, although the code still runs.