A general-purpose tool for dynamic report generation in R
Chunk options can also be written inside a code chunk now after the special comment #|
, e.g.,
```{r}
#| echo = FALSE, fig.width = 10,
#| fig.cap = "This is a long caption."
plot(cars)
```
The main differences between this new syntax and traditional syntax (i.e., chunk options in the chunk header) are: 1) the chunk options can be freely wrapped, i.e., you can write them on as many lines as you prefer; 2) you can also use the YAML syntax instead of the comma-separated syntax if you like, e.g.,
```{r}
#| echo: false
#| fig.width: 10
```
Chunk options provided inside a code chunk will override options with the same names in the chunk header if chunk options are provided in both places, e.g.,
```{r, echo = TRUE}
#| echo = FALSE, fig.width = 10
```
The effective chunk options for the above chunk are echo = FALSE
and fig.width = 10
.
For R Markdown documents, if the chunk header is indented, the closing backticks (usually ```
) of the chunk must be indented with the same amount of spaces (thanks, @atusy, #2047). For example, the following is no longer a valid code chunk because the chunk header is indented but the closing backticks are not:
```{r}
1 + 1
```
If you see an error "attempt to use zero-length variable name" when knitting an Rmd document, it may be because of this change, and you may have indented the chunk header by accident. If that is the case, you need to remove the extra white spaces before the chunk header.
The same problem applies to blockquotes, i.e., >
before ```
. If you quote the chunk header, you have to quote the footer as well, e.g.,
> ```{r}
1 + 1
```
The above unbalanced code chunk needs to be corrected to:
> ```{r}
> 1 + 1
> ```
Quoting the chunk body is optional but recommended.
Fixed a regression in v1.34: now blank lines in code chunks are stripped only when collapse = FALSE
but no longer stripped by default when collapse = TRUE
. If you prefer blank lines to be always stripped, set strip.white = TRUE
globally or on the per chunk basis (thanks, @IndrajeetPatil, rstudio/rmarkdown#2220, #2046).
In knitr::combine_words()
, when words
is length 2 and and = ""
, sep
will now be used (thanks, @eitsupi, #2044).
For R Markdown documents, if the chunk output contains N backticks, the output
hook will use N + 1 backticks to wrap the output, so that the N verbatim backticks can be correctly preserved (thanks, @atusy, #2047).
Added a package option latex.tilde
so that users can customize the tilde symbol, e.g., you can set knitr::opts_knit$set(latex.tilde = "\\hlopt{\\scriptsize{\\ensuremath{\\sim}}}")
. This is because the default tilde is too high in the PDF output, and it's often more desirable to use a middle tilde instead (thanks, @brry #1992, @jaredlander #492).
For the tikz
engine, the class options of the standalone
document classs can be specified via the chunk option engine.opts$classoption
(thanks, @XiangyunHuang, #1985). The default value is tikz
, i.e., \documentclass[tikz]{standalone}
is used by default.
Added the ability to pass additional arguments to dvisvgm
when using the tikz
engine with fig.ext = "svg"
by using dvisvgm.opts
in engine.opts
(thanks, @andrewheiss, #2039). Recent versions of dvisvgm
now allow you to embed fonts into SVG files as base64-encoded WOFF files, so tikz
chunks can embed fonts using like so: ```{tikz, fig.ext="svg", engine.opts=list(dvisvgm.opts = "--font-format=woff")}
.
Added a new targets
engine (https://github.com/ropensci/targets/issues/503, @wlandau). Details: https://books.ropensci.org/targets/markdown.html.
The chunk option cache.globals
can take values TRUE
and FALSE
now (in addition to a character vector). When FALSE
, it tries to find all symbols in the code chunk, no matter if they are local or global variables. When NULL
or TRUE
, it tries to find all global variables (thanks, @knokknok, #1898).
An error is now thrown when an inline code result is not coercible to character. This has always been the assumed behavior but it happens to be different in certain formats with unknown automatic coercion. This is now enforced to prevent any unexpected output. An inline code expression must evaluate to a character vector or an object coercible by as.character()
(#2006).
The markdown package has been moved from Imports
to Suggests
in knitr's DESCRIPTION
, which means it is no longer a hard dependency but has become a soft dependency of knitr (#1864). One consequence for package developers is that if you use the vignette engines based on markdown (such as knitr::knitr
), you will have to explicitly declare the (soft) dependency on markdown, because the implicit dependency through knitr is no longer there.
For R packages that use the knitr::rmarkdown
engine to build their vignettes, rmarkdown
must be declared as a dependency in the package DESCRIPTION
(e.g., in Suggests
). Previously, knitr would fall back to using the markdown package to build vignettes if rmarkdown is not declared (#1864, #2020).
write_bib()
only uses the first URL if multiple are found in a package (#2028).
The attribute data-external="1"
will be added to <iframe>
s generated by include_url()
to prevent Pandoc from embedding the URL as base64 data (thanks, @IndrajeetPatil, https://stackoverflow.com/q/67477667/559676).
The chunk option strip.white = TRUE
used to work only when the chunk option collapse = FALSE
. Now the two options are independent, i.e., strip.white
also works when collapse = TRUE
(thanks, @kbvernon, #2011).
When building R Markdown vignettes but Pandoc is not available, the vignette engine will emit a message instead of a warning before falling back to using the markdown package.
The internal function is_abs_path()
has been removed. Users (if any) should use the exported function xfun::is_abs_path()
instead.
Fix an issue with the RStudio IDE when using knitr::include_url()
or knitr::include_app()
in interactive Notebook mode. This will no more cause an error but print the list object as is (thanks, @systemnova, #2015).
Fix a regression with fig.keep
chunk option used in chunks with only one figure where the figure was not showing in output (thanks, @fmichonneau, #1993).
Allow vignettes to be tangled (and output compared) in R CMD check
if they have a corresponding .Rout.save
(thanks, @lentinj, #2018).
Exported the internal functions sew()
(previously named wrap()
) and is_low_change()
to make it possible for other graphics systems such as rgl to work in knitr like base and grid graphics in base R (thanks, @dmurdoch, #1892 #1853).
For sql
code chunks, parameterized queries will be executed through native database api if the chunk option params
is provided (thanks, @byapparov, #1987).
{}
before [
).wrap()
has been renamed to sew()
.For package vignettes that use the vignette engine knitr::docco_linear
or knitr::docco_classic
, knitr will signal an error during R CMD build
if the markdown package is not declared as a soft dependency in the Suggests
field in DESCRIPTION
. The same treatment has been applied in the previous version of knitr for the vignette engine knitr::knitr
(#1864).
R CMD build
will signal an error when a package uses R Markdown vignettes to be build with the rmarkdown package but the rmarkdown package is not installed (thanks, @nsheff, #1864).
The force_v1
argument of knit2html()
defaults to getOption('knitr.knit2html.force_v1', FALSE)
now, which means its value can be configured via a global option.
The chunk option ref.label
can be used to reuse code from other code chunks in the current code chunk. Now it can also accept a character vector of chunk labels wrapped in I()
so that the chunk options of other code chunks can also be applied to the current chunk. For example, if we have a chunk ```{r, chunk-a, echo=FALSE, results='asis'}
, the chunk ```{r, chunk-b, ref.label=I('chunk-a')}
will inherit both the code and chunk options from chunk-a
(e.g., echo=FALSE
and results='asis'
), but chunk-b
can still override these chunk options, e.g., the actual chunk options of ```{r, chunk-b, echo=TRUE}
will be echo=TRUE
and results='asis'
. If you want to use one code chunk with several chunk options for multiple times, and each time you want to change a small subset of the chunk options, you may use this approach ref.label = I()
to avoid typing most chunk options over and over again (thanks, @atusy, #1960).
The chunk option opts.label
gained a new usage. It used to mean labels in knitr::opts_template
(see the help page if you are not familiar with this object). Now it can also be used to specify the labels of other code chunks, from which the chunk options are to be inherited to the current chunk. For example, ```{r, chunk-b, opts.label='chunk-a'}
means that chunk-b
will inherit chunk options from chunk-a
. Local chunk options in a chunk (if exist) will override inherited options. For the new features about both chunk options ref.label
and opts.label
, see the detailed documentation and examples at https://yihui.org/knitr/options/ (thanks, @atusy, #1960).
The internal code to process R code chunks was factored out into the language engine R
, which can be obtained via knit_engines$get('R')
now (thanks, @abhsarma, #1963).
Added arguments dir
and envir
to load_cache()
to specify the working directory and environment into which the cached objects are loaded. By default, all cached objects are loaded into the global environment, which may not be desirable (thanks, @LTLA, #1905).
The internal function html_screenshot()
, which takes screenshots of HTML widgets and Shiny apps in knitr documents, now prefers the webshot2 package over the webshot package. This is because the backend of the webshot package is PhantomJS, which has been archived since 2018. If webshot is still preferred, use the chunk option opts_chunk$set(webshot = "webshot")
(thanks, @atusy #1918, @LouisStAmour #1858).
Added a new engine, bslib
, which is a special scss
/sass
engine for writing Sass code that wants to leverage Bootstrap Sass. It's primarily designed to work with rmarkdown::html_document_base
's theme
parameter (when it represents a bslib::bs_theme()
), but the engine can be used anywhere a bslib::bs_theme()
is set globally with bslib::bs_global_set()
(thanks, @cpsievert, #1666).
When the chunk option include = FALSE
, error = TRUE
used to be ignored, i.e., errors are signaled nonetheless (causing the knitting process to fail). To avoid this problem, you can now use the numeric value error = 0
so that knitr will not check the include
option, i.e., knitting will not fail even if include = FALSE
and an error has occurred in a code chunk, which you wouldn't notice (thanks, @rundel, #1914).
When processing package vignettes that require rmarkdown or markdown, we now check that it is declared as a package dependency in the DESCRIPTION
file (thanks, @dmurdoch, #1919).
For tikz
code chunks, a new option engine.opts$extra.preamble
allows arbitrary LaTeX code to be inserted into the preamble of the template. This allows loading of additional LaTeX and tikz libraries without having to recreate a template from scratch (thanks, @krivit, #1886).
Fixed an issue where code source and results would not show when using a numeric vector in fig.keep
to select all plots (thanks, @dongzhuoer @ajrgodfrey #1579, @cderv #1955).
Graphical parameter par(col =)
is now preserved as expected in following chunks when knitr::opts_knit$set(global.par = TRUE)
(thanks, @ArnonL, @RolandASc, #1603).
Fixed an issue with kable(format = "latex", booktabs = TRUE)
when the first cell of the table stats with [
(thanks, @jonnypenarth, #1595).
For child documents, include_graphics(error = FALSE)
is the default now (#1957).
For Rnw documents, the commented %\begin{document}
will no longer cause trouble (thanks, @NewbieKnitter @shrektan, #1819).
Fixed an issue with the chunk option fig.alt
causing figures to disappear in rmarkdown::word_document()
output. This option is currently supported for HTML output only. If provided for office output in rmarkdown, it will emit a warning and be ignored (#1966).
Spaces in messages were not properly escaped in .Rnw
documents (thanks, @elbersb, #1978).
The hook hook_pdfcrop()
did not crop figures generated by the tikz
or dot
engine (thanks, @giabaio yihui/xaringan#285, @cderv #1923).
For Rnw documents, if a chunk's output ends with \n
, knitr will no longer add another \n
to it (thanks, @krivit #1958, @jpritikin 1092).
For kable(x, format = 'simple')
, it no longer generates a pipe
table but a simple
table instead when x
has only one column (thanks, @alusiani, #1968). For kable(x, format = 'pipe')
, it no longer warns when x
has no column names, but just generate an empty table header.
For tikz
code chunks, the default LaTeX template uses \documentclass[tikz]{standalone}
instead of \documentclass{article}
and \usepackage{preview}
now (thanks, @XiangyunHuang, #1985).
Exported the functions pandoc_to()
and pandoc_from()
to get the output and input Pandoc format respectively when knitting R Markdown documents (thanks, @cderv, #1951).
Added a new chunk option fig.alt
for users to specify the alternative text in the alt
attribute of the <img>
tag (images). Previously, the alt
attribute takes value from the chunk option fig.cap
(it still does so if fig.alt
is NULL
). If there are multiple plots/images in a chunk, you can pass a character vector to fig.alt
, and it will be applied to individual images (thanks, @cderv, #1900).
include_url()
and include_app()
can now take a vector of URLs (thanks, @cderv, #1948).
The sql
engine now correctly captures error with the chunk option error = TRUE
(thanks, @colearendt, rstudio/rmarkdown#1208).
The chunk option collapse = TRUE
now works as expected when the chunk option attr.*
or class.*
is provided. By this change, The chunk option collapse = TRUE
forces attr.*
and class.*
be NULL
except for the chunk options attr.source
and class.source
(thanks, @aosavi @cderv @atusy, #1902 #1906).
New links added in ?knitr::kable()
help page to the Rmarkdown Cookbook relevant pages.
The table label can be disabled via kable(label = NA)
now (thanks, @NickCH-K, #1937).
The table.attr
argument in kable(.., format = 'html')
can take the value from the global option knitr.table.html.attr
now (thanks, @cderv, #1922).
Added a new argument oxford_comma
to the function combine_words()
(thanks, @thompsonsed, #1946).
The label prefix of tables generated by kable()
can be customized via the package option label.prefix
in opts_knit
now. This option takes a named character vector, and the default is knitr::opts_knit$set(label.prefix = c(table = 'tab:'))
. If you want to use a different prefix such as tbl
, you may set the option to c(table = 'tbl:')
(thanks, @luispfonseca, #1890).
The global option options(knitr.device.fallback = TRUE)
can be used to allow the graphical device specified in the chunk option dev
to fall back to other usable devices if the specified device is not operational. Users can provide a list of fallback devices via the global option, e.g., options(knitr.device.choices = list(png = c('jpeg', 'svg'), jpeg = c('tiff')))
, which means the png
device can fall back to jpeg
and svg
(the first operational device in the list is used) and jpeg
can fall back to tiff
.
knit_exit()
in a child document would not terminate the knitting process of its parent document. Now it will terminate the whole process by default. You can use knit_exit(fully = FALSE)
to exit the child document only (thanks, @davidchall, #1810).pandoc-citeproc
since it has gone since Pandoc 2.11.Added knitr::hooks_*()
functions to get a list of output hooks for a specific format. Previously, these hooks only exist inside the knitr::render_*()
functions, and users do not have direct access to them. Now they can be accessed directly, e.g., via knitr::hooks_markdown()
to get a list of output hooks for R Markdown documents. You can also set the output hooks individually, e.g., knitr::knit_hooks$set(knitr::hooks_markdown()['source'])
only sets the source ouput hook. See more on output hooks at https://yihui.org/knitr/hooks/#output-hooks and https://bookdown.org/yihui/rmarkdown-cookbook/output-hooks.html (thanks, @cderv, #1889).
Added an argument lib.loc
to knitr::write_bib()
.
The option fig_caption = FALSE
for rmarkdown::html_document()
was unable to suppress the figure captions in some cases.
The internal function fix_options()
should be called after option hooks are executed (thanks, @atusy, #1876 and #1877).
When the option options(OutDec = )
is set to a value other than "."
, percentages in the chunk options out.width
and out.height
do not work (thanks, @omgitsmoe, #1887).
knitr::write_bib()
removes pairs of single quotes in the titles of citation entries now.
knitr::write_bib()
uses the URL
in the package DESCRIPTION
if it is provided, instead of the canonical CRAN URL for the package.
hook_pdfcrop()
and plot_crop()
will work only when both programs pdfcrop
and ghostscript
have been installed. Previously only pdfcrop
was checked (thanks, @dalupus, #954).
Added a new function kables()
(the plural form of kable()
) to create a table containing multiple tables, with each table created by kable()
. Previously you can only create such a table from kable(list(data1, data2))
, and now you can also do kables(list(kable(data1), kable(data2)))
. The latter way gives you more freedom to control each table individually via the arguments of each individual kable()
call.
The graphics device chunk option, dev
, now supports a value of 'ragg_png'
which calls the agg_png()
function from the ragg package (thanks, @cpsievert, #1834).
The argument error
of include_graphics()
takes value from the global R option knitr.graphics.error
by default, e.g., you may set options(knitr.graphics.error = FALSE)
so include_graphics()
won't signal an error if the graphics file to be included doesn't exist.
Added a new engine cc
to compile C++ code via R CMD SHILIB
like the c
and fortran
engines (thanks, @kingaa, #1832).
For non-R code chunks that generate plots and use the chunk option fig.cap
, the plot
hook in knitr stopped working in v1.27 and v1.28 (thanks, @XiangyunHuang, https://d.cosx.org/d/421249).
The sql
engine fails when the first column of the database is of the type bit64::integer64
(thanks, @randy3k, #1837).
The chunk option dpi
is correctly passed to showtext::showtext_opts()
now (thanks, @cpsievert, yixuan/showtext#33).
Theorem environments in bookdown fail to work with Pandoc >= 2.7.3 because of an issue in the block2
engine of knitr (rstudio/bookdown#883).
For R Markdown documents, the default table format generated by kable()
was changed from Pandoc's simple tables to pipe tables. This fixes bugs #1788 (kable()
fails to align columns containing wide characters) and #1817 (broken column headers) (thanks, @atusy, #1830).
When a code chunk generates multiple plots to be placed in figure environments, their figure labels will be of the form label-i
where label
is the chunk label, and i
is the plot number. Previously, the labels were of the form labeli
(i.e., there was not a dash before the number). If you cross-reference the figures, you need to change the reference keys from labeli
to label-i
.
For a non-matrix object passed to kable()
, its columns are formatted individually via format()
. Previously, the whole object is coerced via as.matrix()
(thanks, @thebioengineer, #1827).
For packages that contain R Markdown vignettes using the vignette engines based on the markdown package (e.g., knitr::knitr
), the markdown package should be declared in Suggests
in the package DESCRIPTION
unless it has already been declared as a dependency in other fields. For this version of knitr, you will see a warning in R CMD check
in the CRAN incoming check. In the future, you may see a warning in a regular R CMD check
, so please add markdown to Suggests
at your earliest convenience. If it is not clear how to do it, please see #1864.
knitr::image_uri()
calls xfun::base64_uri()
instead of markdown:::.b64EncodeFile()
now.
knitr::write_bib()
now adds an empty line after each BibTeX entry (#1862).
hook_pdfcrop()
no longer crops images included via include_graphics()
now (thanks, @hpages #1797, @salim-b #1800).If the hook_pdfcrop()
is enabled, the non-PDF image will be cropped only if the magick package is available, otherwise it will signal a message. In the previous version, it will signal an error (thanks, @trannhatanh89, #1796).
By default, include_graphics(files)
will signal an error if any files
do not exist and are not web resources. To avoid the error (e.g., if you think it is a false positive), use include_graphics(..., error = FALSE)
(thanks, @hadley, #1717).
message = FALSE
can now be used to suppress the message "running: command ..." when the language engine is a command such as bash
, awk
, perl
, ruby
, sas
, sed
, and stata
, etc. (thanks, @splaisan, #1782).The figure caption was placed incorrectly when there are multiple include_graphics()
in a code chunk (thanks, @hadley #1771, @cderv #1776).
The chunk option fig.keep
was buggy when taking a numeric vector. The bug was originally introduced in #1265 and discovered in the SO post https://stackoverflow.com/q/59180351/559676.
When the chunk option dev = 'tikz'
and a plot in the code chunk is generated by ggplot2 with a legend on a continuous scale, tikzDevice will create a raster image for the legend. Now the path to the raster image in the .tex
file is tweaked to include the dir name of the .tex
file, so that the .tex
file can be correctly compiled to PDF via LaTeX (thanks to @rstub for the debugging at https://stackoverflow.com/a/58410965/559676).
hook_pdfcrop()
does not crop all plots when multiple graphical devices are used in a code chunk (i.e., the chunk option dev
takes a vector of devices) due to a bug in the internal function all_figs()
identified by @bastistician in #1766, who also proposed a fix.
options('width')
no longer affects caching. With this change, your previous cache will be invalidated if you update knitr from 1.26 to 1.27. If you prefer that changes in the R global option width
invalidate cache (as in previous versions of knitr), you may associate it with a chunk option, e.g., cache.extra = getOption('width')
. The reason for this change is that it is too costly to invalidate the cache when the width
option changes---the effect of this option is only cosmetic and the code chunk output may not really rely on this option (thanks, @jaburgoyne, #1781).is_html_output()
returns TRUE
for the Pandoc output format gfm
now (thanks, @ttimbers @cderv, rstudio/rmarkdown#1756).
plot_crop()
no longer calls the convert
command in ImageMagick to trim non-PDF plots. Instead, the function magick::image_trim()
is called. This means you no longer need to install ImageMagick, but should install the R package magick (thanks, @hpages, #1785).
When the chunk option fig.scap
is used in R Markdown and the output format is LaTeX/PDF, the plot hook knitr::hook_plot_tex()
will be used to create the appropriate figure environment. In previous versions, fig.scap
is silently ignored (thanks, @billdenney, #1793).