knit_print: A custom printing function

View source: R/output.R

knit_printR Documentation

A custom printing function


The S3 generic function knit_print is the default printing function in knitr. The chunk option render uses this function by default. The main purpose of this S3 generic function is to customize printing of R objects in code chunks. We can fall back to the normal printing behavior by setting the chunk option render = normal_print.


knit_print(x, ...)

normal_print(x, ...)



An R object to be printed


Additional arguments passed to the S3 method. Currently ignored, except two optional arguments options and inline; see the references below.


Users can write custom methods based on this generic function. For example, if we want to print all data frames as tables in the output, we can define a method that turns a data.frame into a table (the implementation may use other R packages or functions, e.g. xtable or kable()).


The value returned from the print method should be a character vector or can be converted to a character value. You can wrap the value in asis_output() so that knitr writes the character value as is in the output.


It is recommended to leave a ... argument in your method, to allow future changes of the knit_print() API without breaking your method.


See vignette('knit_print', package = 'knitr').


# write tables for data frames = function(x, ...) {
    res = paste(c("", "", kable(x, output = FALSE)), collapse = "\n")
# register the method
registerS3method("knit_print", "data.frame",
# after you define and register the above method, data frames will be printed
# as tables in knitr, which is different with the default print() behavior

knitr documentation built on Nov. 2, 2023, 5:49 p.m.