1.6 Advanced Code Chunks and Output
In Section 1.4, we introduced the basics of code chunks and a few commonly used chunk options. In this section, we explore more advanced chunk options and techniques for controlling how your code and its output appear in the final document.
1.6.1 Figure Options
When a code chunk produces a plot, you can control its appearance with several chunk options.
fig.widthandfig.height: Set the dimensions of the plot in inches.fig.cap: Add a caption to the figure.fig.align: Align the figure ("left","center", or"right").out.widthandout.height: Control the display size in the output document (e.g.,"80%"or"400px").
Here is an example:
```{r my-plot, fig.width=8, fig.height=5, fig.cap="Scatterplot of pressure vs. temperature", fig.align="center", out.width="80%"}
plot(pressure)
```When you provide fig.cap, the figure is automatically numbered and can be cross-referenced with \@ref(fig:my-plot) in bookdown.
1.6.2 Caching
For code chunks that take a long time to run (e.g., fitting complex models or processing large datasets), you can use caching to save the results so they are not recomputed every time you knit.
```{r slow-computation, cache=TRUE}
# This chunk will only run once; results are cached
result <- replicate(10000, mean(rnorm(1000)))
```Be cautious with caching: if the data or code that a cached chunk depends on changes, the cached result may be stale. You can use cache.extra or dependson options to manage dependencies.
1.6.3 Controlling Output
You can fine-tune what appears in the knitted document:
| Option | Effect |
|---|---|
results = "hide" |
Run the code but hide text output |
results = "hold" |
Hold all output until the end of the chunk |
results = "asis" |
Treat output as raw Markdown (useful for tables) |
collapse = TRUE |
Merge code and output into a single block |
tidy = TRUE |
Reformat code for consistent style |
1.6.4 Inline Code Revisited
Recall from Section 1.5 that you can embed R expressions directly in your text. This is especially powerful for dynamic reports.
For example, you might write:
We have assigned
x <- 5. The cube ofxis`r x^3`.
This renders as: “We have assigned x <- 5. The cube of x is 125.” The number updates automatically if you change the value of x earlier in the document.
1.6.5 Setting Chunk Options for the Whole Document
In addition to the global chunk options introduced in Section 1.4, you can use the knitr::opts_chunk$set() function to configure many options at once.
knitr::opts_chunk$set(
echo = TRUE,
warning = FALSE,
message = FALSE,
fig.width = 7,
fig.height = 5,
fig.align = "center"
)Individual chunks can still override these global settings as needed.
1.6.6 Exercises
Create an R Markdown document that produces a scatterplot with a caption. Use
fig.cap,fig.width = 8, andfig.align = "center".Write a code chunk that simulates drawing 100,000 random numbers from a normal distribution and computing their mean. Enable caching with
cache = TRUE. Knit the document twice and observe the speed difference.Create a code chunk that produces a formatted table using
knitr::kable()withresults = "asis". Verify that the table renders correctly in the knitted output.Write a paragraph that uses inline R code to calculate and report the value of
exp(3) / log(20, 3) * 7. The number should evaluate directly within the text.