Chapter 12 Output Hooks (*)

    Consider this code chunk with one line of code:

    After knitr evaluates the code chunk, it gets two output elements, and both are stored as character strings: the source code , and the text output "[1] 2". These character strings will be further processed by chunk hooks for the desired output format. For example, for Markdown documents, knitr will wrap the source code in a fenced code block with a language name. This is done through the source hook, which more or less looks like this function:

    1. # for the above case, `x` is a character string '1 + 1'
    2. function(x, options) {
    3. # the little 'r' here indicates the language name
    4. paste(c("```r", x, "```"), collapse = "\n")
    5. }

    Similarly, the text output is processed by the output hook that looks like this function:

    So the final output of the above code chunk is:

    1. ```r
    2. 1 + 1
    3. ```
    4. [1] 2
    5. ```

    The actual hooks are more complicated than the two functions above, but the idea is the same. You may obtain the actual hooks from the object knit_hooks via the method, e.g.,

    A custom output hook is registered through the set() method of knit_hooks. Because this method will override the existing default hook, we recommend that you save a copy of an existing hook, process the output elements in your own way, and pass the results to the default hook. The usual syntax is:

    1. # using local() is optional here (we just want to avoid
    2. # creating unnecessary global variables like `hook_old`)
    3. local({
    4. hook_old <- knitr::knit_hooks$get("NAME") # save the old hook
    5. knitr::knit_hooks$set(NAME = function(x, options) {
    6. # now do whatever you want to do with x, and pass the
    7. # new x to the old hook
    8. })
    9. })

    Here, NAME is the name of the hook, which can be one of the following values:

    • source: processing the source code.

    • : processing text output.

    • warning: processing warnings (usually from warning()).

    • error: processing error messages (usually from stop()).

    • plot: processing plot file paths.

    • inline: processing output from inline R expressions.

    • document: processing the whole document.

    Output hooks give you the ultimate control over every single piece of your chunk and document output. Compared with chunk options, which often have predefined purposes, output hooks can be much more powerful since they are user-defined functions, and you can do anything you want in functions.