
Include an HTML-renderable object in any knitr output format
Source:R/knit_include.R
knit_include.RdA pipe-friendly helper in Rmarkdown, Quarto, and other documents for objects that render natively in HTML output
(RStudio Viewer, HTML documents) but need a convenient image fallback for PDF, Word,
and other non-HTML formats. It was designed to solve a problem in rendering the result of color_table(),
and then generalized to provide for other similar cases.
Usage
knit_include(
x,
file = tempfile("ki_", tmpdir = "."),
width = 700,
height = 400,
...
)Arguments
- x
Any R object. Specialised handling for
gt_tblandhtmlwidget; all other classes are passed through unchanged.- file
Base filename (no extension) for temporary files written when output is not HTML. Defaults to a session-unique temp file in the current directory so multiple calls don't collide.
- width
Viewport / screenshot width in pixels (non-HTML only).
- height
Viewport / screenshot height in pixels (non-HTML only).
- ...
Value
For gt_tbl / htmlwidget in non-HTML output: the result
of include_graphics. Otherwise: x
unchanged.
Details
Supported classes (handled internally) solve this problem by saving the image to a file and then inserting it in the document
using knitr::include_graphics():
"gt_tbl"(gt package) – saved viagtsave"htmlwidget"(htmlwidgets family: plotly, DT, leaflet, dygraphs, ...) – saved viasaveWidget+webshot
Packages that handle cross-format output natively (flextable, kableExtra, huxtable) do NOT need this helper.
For any other class, x is returned as-is in all output formats and
knitr's normal printing applies. This means the function is safe to use in
a pipe on any object: it only intervenes when it knows how to help!
Examples
if (FALSE) { # \dontrun{
data(HairEyeColor)
HEC <- margin.table(HairEyeColor, 1:2)
## gt_tbl from color_table()
color_table(HEC, title = "Hair x Eye Color") |> knit_include()
## DT htmlwidget
DT::datatable(mtcars) |> knit_include(width = 900, height = 500)
## plotly htmlwidget
plotly::plot_ly(mtcars, x = ~wt, y = ~mpg) |> knit_include()
## Any other object passes through unchanged
lm(mpg ~ wt, data = mtcars) |> knit_include()
} # }