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:
names(knitr:::.default.hooks)
## [1] "source" "output"
## [3] "warning" "message"
## [5] "error" "plot"
## [7] "inline" "chunk"
## [9] "text" "evaluate.inline"
## [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
:
::knit_hooks$set(greet = function(before) {
knitrif (before)
"Hello!" else "Bye!"
})
We will explain the arguments of the hook function in a moment. Now we set the chunk option greet = TRUE
for the chunk below:
```{r, greet=TRUE}
1 + 1
```
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] 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:
function(before, options, envir, name) {
}
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 withhook(before = TRUE)
and once after withhook(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.