13.4 Show the chunk header in the output

Sometimes you may want to show the original code chunk header to your readers. For example, when you write an R Markdown tutorial, you may want to show both the chunk output and the chunk options that you used to generate the output, so your readers can learn how to do it by themselves.

The original chunk options are actually stored as a character string in the chunk option params.src. After you know this, you may write a chunk hook to add params.src to the output. Below is a full example:

title: Show chunk headers in the output

Set up a chunk hook named `wrapper` to wrap the chunk
output inside the original chunk header and footer.

```{r, setup, include=FALSE}
knitr::knit_hooks$set(wrapper = function(before, options) {
  # the original chunk might be indented
  if (is.null(indent <- options$indent)) indent <- ''
  # hide the wrapper=TRUE option
  opts <- gsub(', wrapper=TRUE', '', options$params.src)
  if (before) {
    # add the header
    sprintf('\n\n%s````\n```{r,%s}\n````\n', indent, opts)
  } else {
    # add the footer
    sprintf('\n\n%s````\n```\n````\n', indent)

Now we apply the hook via the chunk option `wrapper=TRUE`.
Remember to put `wrapper=TRUE` at the end of the header, and
it has to be `wrapper=TRUE` precisely (e.g., not `wrapper=T`),
following a comma and a space, unless you adjust the `gsub()`
call in the above hook.

```{r, test-label, collapse=TRUE, wrapper=TRUE}
1 + 1

You should see the original chunk header appear in
the output. The hook should also work when the chunk
is indented, e.g.,

- One bullet.

  ```{r, eval=TRUE, wrapper=TRUE}
  2 + 2

- Another bullet.

Basically, we restored the chunk header from options$params.src by putting this string inside ```{r, }. Then we wrapped this line in a pair of four backticks, so it can be displayed verbatim in the output. Note that the original code chunk might be indented (e.g., when it is nested in a list item), so we also need to add the proper indentation, which is stored in the chunk option options$indent.

The output of the bullet list at the end of the above example will be like this:

  • One bullet.

    ```{r, eval=TRUE}
    2 + 2
    ## [1] 4
  • Another bullet.

You can see that the code chunk was evaluated, and the chunk header was also added.