Code Cells: Knitr

Knitr is an R package for dynamic document generation. Learn more about using Knitr in the article on Using R.


Cell options affect the execution and output of executable code blocks. They are specified within comments at the top of a block. For example:

#| label: fig-polar
#| echo: false
#| fig-cap: "A line plot on a polar axis"



Unique label for code cell. Used when other code needs to refer to the cell (e.g. for cross references fig-samples or tbl-summary)


Classes to apply to cell container

Code Output


Evaluate code cells (if false just echos the code into output).

  • true (default): evaluate code cell
  • false: don’t evaluate code cell
  • [...]: A list of positive or negative line numbers to selectively include or exclude lines (explicit inclusion/excusion of lines is available only when using the knitr engine)

Include cell source code in rendered output.

  • true (default): include source code in output
  • false: do not include source code in output
  • fenced: in addition to echoing, include the cell delimiter as part of the output.
  • [...]: A list of positive or negative line numbers to selectively include or exclude lines (explicit inclusion/excusion of lines is available only when using the knitr engine)

Collapse code into an HTML <details> tag so the user can display it on-demand.

  • true: collapse code
  • false (default): do not collapse code
  • show: use the <details> tag, but show the expanded code initially.

Summary text to use for code blocks collapsed using code-fold


Choose how to handle code overflow, when code lines are too wide for their container. One of:

  • scroll
  • wrap

Include line numbers in code block output (true or false).

For revealjs output only, you can also specify a string to highlight specific lines (and/or animate between sets of highlighted lines).

  • Sets of lines are denoted with commas:
    • 3,4,5
    • 1,10,12
  • Ranges can be denoted with dashes and combined with commas:
    • 1-3,5
    • 5-10,12,14
  • Finally, animation steps are separated by |:
    • 1-3|1-3,5 first shows 1-3, then 1-3,5
    • |5|5-10,12 first shows no numbering, then 5, then lines 5-10 and 12

Unique label for code listing (used in cross references)


Caption for code listing


Whether to reformat R code.


List of options to pass to tidy handler


Collapse all the source and output blocks from one code chunk into a single block


Whether to add the prompt characters in R code. See prompt and continue on the help page ?base::options. Note that adding prompts can make it difficult for readers to copy R code from the output, so prompt: false may be a better choice. This option may not work well when the engine is not R (#1274).


Class name(s) for source code blocks


Attribute(s) for source code blocks

Cell Output


Include the results of executing the code in the output. Possible values:

  • true: Include results.
  • false: Do not include results.
  • asis: Treat output as raw markdown with no enclosing containers.

Include warnings in rendered output.


Include errors in the output (note that this implies that errors executing code will not halt processing of the document).


Catch all for preventing any output (code or results) from being included in output.


Panel type for cell output (tabset, input, sidebar, fill, center)


Location of output relative to the code that generated it. The possible values are as follows:

  • default: Normal flow of the slide after the code
  • fragment: In a fragment (not visible until you advance)
  • slide: On a new slide after the curent one
  • ‘column’: In an adjacent column
  • column-fragment: In an adjacent column (not visible until you advance)

Note that this option is supported only for the revealjs format.


Include messages in rendered output.


How to display text results. Note that this option only applies to normal text output (not warnings, messages, or errors). The possible values are as follows:

  • markup: Mark up text output with the appropriate environments depending on the output format. For example, if the text output is a character string "[1] 1 2 3", the actual output that knitr produces will be:

    [1] 1 2 3

    In this case, results: markup means to put the text output in fenced code blocks (```).

  • asis: Write text output as-is, i.e., write the raw text results directly into the output document without any markups.

    #| results: asis
    cat("I'm raw **Markdown** content.\n")
  • hold: Hold all pieces of text output in a chunk and flush them to the end of the chunk.

  • hide (or false): Hide text output.


Prefix to be added before each line of text output. By default, the text output is commented out by ##, so if readers want to copy and run the source code from the output document, they can select and copy everything from the chunk, since the text output is masked in comments (and will be ignored when running the copied text). Set comment: '' to remove the default ##.


Class name(s) for text/console output


Attribute(s) for text/console output


Class name(s) for warning output


Attribute(s) for warning output


Class name(s) for message output


Attribute(s) for message output


Class name(s) for error output


Attribute(s) for error output



Default width for figures


Default height for figures


Figure caption


Figure subcaptions


Hyperlink target for the figure


Figure horizontal alignment (default, left, right, or center)


Alternative text to be used in the alt attribute of HTML images.


LaTeX environment for figure output


LaTeX figure position arrangement to be used in \begin{figure}[].

Computational figure output that is accompanied by the code that produced it is given a default value of fig-pos="H" (so that the code and figure are not inordinately separated).


A short caption (only used in LaTeX output). A short caption is inserted in \caption[], and usually displayed in the “List of Figures” of a PDF document.


Default output format for figures (retina, png, jpeg, svg, or pdf)


Default DPI for figures


The aspect ratio of the plot, i.e., the ratio of height/width. When fig-asp is specified, the height of a plot (the option fig-height) is calculated from fig-width * fig-asp.


Width of the plot in the output document, which can be different from its physical fig-width, i.e., plots can be scaled in the output document. Depending on the output format, this option can take special values. For example, for LaTeX output, it can be .8\\linewidth, 3in, or 8cm; for HTML, it can be 300px or 50%.


Height of the plot in the output document, which can be different from its physical fig-height, i.e., plots can be scaled in the output document. Depending on the output format, this option can take special values. For example, for LaTeX output, it can be 3in, or 8cm; for HTML, it can be 300px.


How plots in chunks should be kept. Possible values are as follows:

  • high: Only keep high-level plots (merge low-level changes into high-level plots).
  • none: Discard all plots.
  • all: Keep all plots (low-level plot changes may produce new plots).
  • first: Only keep the first plot.
  • last: Only keep the last plot.
  • A numeric vector: In this case, the values are indices of (low-level) plots to keep.

How to show/arrange the plots. Possible values are as follows:

  • asis: Show plots exactly in places where they were generated (as if the code were run in an R terminal).
  • hold: Hold all plots and output them at the end of a code chunk.
  • animate: Concatenate all plots into an animation if there are multiple plots in a chunk.
  • hide: Generate plot files but hide them in the output document.

Additional raw LaTeX or HTML options to be applied to figures


Externalize tikz graphics (pre-compile to PDF)


sanitize tikz graphics (escape special LaTeX characters).


Time interval (number of seconds) between animation frames.


Extra options for animations; see the documentation of the LaTeX animate package.


Hook function to create animations in HTML output.

The default hook (ffmpeg) uses FFmpeg to convert images to a WebM video.

Another hook function is gifski based on the gifski package to create GIF animations.



Table caption


Table subcaptions


Apply explicit table column widths for markdown grid tables and pipe tables that are more than columns characters wide (72 by default).

Some formats (e.g. HTML) do an excellent job automatically sizing table columns and so don’t benefit much from column width specifications. Other formats (e.g. LaTeX) require table column sizes in order to correctly flow longer cell content (this is a major reason why tables > 72 columns wide are assigned explicit widths by Pandoc).

This can be specified as:

  • auto: Apply markdown table column widths except when there is a hyperlink in the table (which tends to throw off automatic calculation of column widths based on the markdown text width of cells). (auto is the default for HTML output formats)

  • true: Always apply markdown table widths (true is the default for all non-HTML formats)

  • false: Never apply markdown table widths.

  • An array of numbers (e.g. [40, 30, 30]): Array of explicit width percentages.

Panel Layout


2d-array of widths where the first dimension specifies columns and the second rows.

For example, to layout the first two output blocks side-by-side on the top with the third block spanning the full width below, use [[3,3], [1]].

Use negative values to create margin. For example, to create space between the output blocks in the top row of the previous example, use [[3,-1, 3], [1]].


Layout output blocks into columns


Layout output blocks into rows


Horizontal alignment for layout content (default, left, right, or center)


Vertical alignment for layout content (default, top, center, or bottom)

Page Columns


Page column for output


Page column for figure output


Page column for table output


Where to place figure and table captions (top, bottom, or margin)


Where to place figure captions (top, bottom, or margin)


Where to place table captions (top, bottom, or margin)



Whether to cache a code chunk. When evaluating code chunks for the second time, the cached chunks are skipped (unless they have been modified), but the objects created in these chunks are loaded from previously saved databases (.rdb and .rdx files), and these files are saved when a chunk is evaluated for the first time, or when cached files are not found (e.g., you may have removed them by hand). Note that the filename consists of the chunk label with an MD5 digest of the R code and chunk options of the code chunk, which means any changes in the chunk will produce a different MD5 digest, and hence invalidate the cache.


Variable names to be saved in the cache database. By default, all variables created in the current chunks are identified and saved, but you may want to manually specify the variables to be saved, because the automatic detection of variables may not be robust, or you may want to save only a subset of variables.


Variables names that are not created from the current chunk.

This option is mainly for autodep: true to work more precisely—a chunk B depends on chunk A when any of B’s global variables are A’s local variables. In case the automatic detection of global variables in a chunk fails, you may manually specify the names of global variables via this option. In addition, cache-globals: false means detecting all variables in a code chunk, no matter if they are global or local variables.


Whether to lazyLoad() or directly load() objects. For very large objects, lazyloading may not work, so cache-lazy: false may be desirable (see #572).


Force rebuild of cache for chunk


Prevent comment changes from invalidating the cache for a chunk


Explicitly specify cache dependencies for this chunk (one or more chunk labels)


Detect cache dependencies automatically via usage of global variables



One or more paths of child documents to be knitted and input into the main document.


File containing code to execute for this chunk


String containing code to execute for this chunk


Include chunk when extracting code with knitr::purl()