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.width and fig.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.width and out.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 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.3 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 of x is `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.4 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.5 Exercises

  1. Create an R Markdown document that produces a scatterplot with a caption using plot(pressure). Use fig.cap, fig.width = 8, and fig.align = "center".

  2. Write a code chunk that assigns x <- 10 and y <- 20 and calculates their sum (x + y). Use the chunk option echo = FALSE to only show the result.

  3. 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.


Buy Me A Coffee