Chapter 13 Chunk Hooks (*)

A chunk hook is a function that is triggered by a chunk option when the value of this chunk option is not NULL. Chunk hooks provide a way for you to execute additional tasks beyond running the code in a chunk. For example, you may want to post-process plots (e.g., Section 13.1 and Section 13.2), or record the time taken by a code chunk (Section 13.3). Such tasks may not be essential to the computing or analysis in the report, but they can be useful for other purposes (e.g., enhance plots or help you identify the most time-consuming chunks).

You can use chunk hooks purely for their side effects (e.g., only printing out certain information to the console), or for their returned values, which will be written to the output document if the value is a character value.

Like output hooks (see Chapter 12), chunk hooks are also registered via the object knitr::knit_hooks. Please note that the names of output hooks are reserved by knitr, so you must not use these names for your custom chunk hooks:

  1. names(knitr:::.default.hooks)
  1. ## [1] "source" "output"
  2. ## [3] "warning" "message"
  3. ## [5] "error" "plot"
  4. ## [7] "inline" "chunk"
  5. ## [9] "text" "evaluate.inline"
  6. ## [11] "evaluate" "document"

A chunk hook is associated with a chunk option of the same name. For example, you can register a chunk hook with the name greet:

  1. knitr::knit_hooks$set(greet = function(before) {
  2. if (before)
  3. "Hello!" else "Bye!"
  4. })

We will explain the arguments of the hook function in a moment. Now we set the chunk option greet = TRUE for the chunk below:

  1. ```{r, greet=TRUE}
  2. 1 + 1
  3. ```

And you will see that “Hello!” appears before the chunk, and “Bye!” appears after the chunk in the output below (which is because they are character values):

Hello!

  1. 1 + 1
  1. ## [1] 2

Bye!

A chunk hook function can possibly take four arguments: before, options, envir, and name. In other words, it can be of this form:

  1. function(before, options, envir, name) {
  2. }

All four arguments are optional. You can have four, three, two, one, or even no arguments. In the above example, we used one argument (i.e., before). The meanings of these arguments are:

  • before: Whether the chunk hook is currently being executed before or after the code chunk itself is executed. Note that a chunk hook is executed twice for every code chunk (once before with hook(before = TRUE) and once after with hook(before = FALSE).

  • options: The list of chunk options for the current code chunk, e.g., list(fig.width = 5, echo = FALSE, ...).

  • envir: The environment in which the chunk hook is evaluated.

  • name: The name of the chunk option that triggered the chunk hook.

As we mentioned in the beginning of this chapter, non-character values returned by chunk hooks are silently ignored, and character values are written to the output document.