11.17 Customize the printing of objects in chunks (*)

By default, objects in code chunks are printed through the knitr::knit_print() function, which is by and large just print() in base R. The knit_print() function is an S3 generic function, which means you can extend it by yourself by registering S3 methods on it. The following is an example that shows how to automatically print data frames as tables via knitr::kable():

title: Use a custom `knit_print` method to print data frames

First, we define a `knit_print` method, and register it:

knit_print.data.frame = function(x, ...) {
  res = paste(c("", "", knitr::kable(x)), collapse = "\n")

  "knit_print", "data.frame", knit_print.data.frame,
  envir = asNamespace("knitr")

Now we can test this custom printing method on data frames.
Note that you no longer need to call `knitr::kable()`



You can learn more about the knit_print() function in the knitr package vignette:

vignette("knit_print", package = "knitr")

The printr package (Xie 2017) has provided a few S3 methods to automatically print R objects as tables if possible. All you need is library(printr) in an R code chunk, and all methods will be automatically registered.

If you find this technique too advanced for you, some R Markdown output formats such as html_document and pdf_document also provide an option df_print, which allows you to customize the printing behavior of data frames. For example, if you want to print data frames as tables via knitr::kable(), you may set the option:

    df_print: kable

Please see the help pages of the output format functions (e.g., ?rmarkdown::html_document) to determine whether an output format supports the df_print option and, if so, what the possible values are.

In fact, you can completely replace the printing function knit_print() through the chunk option render, which can take any function to print objects. For example, if you want to print objects using the pander package, you may set the chunk option render to the function pander::pander():

```{r, render=pander::pander}

The render option gives you complete freedom on how to print your R objects.


Xie, Yihui. 2017. Printr: Automatically Print R Objects to Appropriate Formats According to the Knitr Output Format. https://yihui.org/printr/.