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:

  1. ---
  2. title: Show chunk headers in the output
  3. ---
  4. Set up a chunk hook named `wrapper` to wrap the chunk
  5. output inside the original chunk header and footer.
  6. ```{r, setup, include=FALSE}
  7. knitr::knit_hooks$set(wrapper = function(before, options) {
  8. # the original chunk might be indented
  9. if (is.null(indent <- options$indent)) indent <- ''
  10. # hide the wrapper=TRUE option
  11. opts <- gsub(', wrapper=TRUE', '', options$params.src)
  12. if (before) {
  13. # add the header
  14. sprintf('\n\n%s````\n```{r,%s}\n````\n', indent, opts)
  15. } else {
  16. # add the footer
  17. sprintf('\n\n%s````\n```\n````\n', indent)
  18. }
  19. })
  20. ```
  21. Now we apply the hook via the chunk option `wrapper=TRUE`.
  22. Remember to put `wrapper=TRUE` at the end of the header, and
  23. it has to be `wrapper=TRUE` precisely (e.g., not `wrapper=T`),
  24. following a comma and a space, unless you adjust the `gsub()`
  25. call in the above hook.
  26. ```{r, test-label, collapse=TRUE, wrapper=TRUE}
  27. 1 + 1
  28. plot(cars)
  29. ```
  30. You should see the original chunk header appear in
  31. the output. The hook should also work when the chunk
  32. is indented, e.g.,
  33. - One bullet.
  34. ```{r, eval=TRUE, wrapper=TRUE}
  35. 2 + 2
  36. ```
  37. - 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.

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

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