Chapter 13 Chunk Hooks (*)

    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 ), 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. ## [1] "source" "output"
    2. ## [3] "warning" "message"
    3. ## [5] "error" "plot"
    4. ## [7] "inline" "chunk"
    5. ## [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 :

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

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

    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:

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

    • : 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.