Skip to contents

Syntax

format start end inline output
Rnw <<*>>= @ \Sexpr{x} TeX
Rmd ```{r *} ``` `r` `x` Markdown
Rhtml <!--begin.rcode * end.rcode--> <!--rinline x--> HTML
Rrst .. {r *} .. .. :r:`x` reST
Rtex % begin.rcode * % end.rcode \rinline{x} TeX
Rasciidoc // begin.rcode * // end.rcode +r x+ AsciiDoc
Rtextile ### begin.rcode * ### end.rcode @r x@ Textile
brew <% x %> text

* denotes local chunk options, e.g., <<label, eval=FALSE>>=; x denotes inline R code, e.g., 3.

Minimal Examples

Sweave (*.Rnw)

\documentclass{article}
\begin{document}

Below is a code chunk.

<<foo, echo=TRUE>>=
z = 1 + 1
plot(cars)
@

The value of z is \Sexpr{z}.
\end{document}

R Markdown (*.Rmd)

---
title: "An R Markdown document"
---

Hi _Markdown_!


``` r
z = 1 + 1
plot(cars)
```

<img src="/data/user-homes/andrew/Projects/prism-pkgdocs-build/installed-pkgs/2025-12-29/knitr_1.51/docs/articles/knitr-refcard_files/figure-html/foo-1.png" class="r-plt" alt="" width="700" />

The value of z is 2.

Chunk Options

opts_chunk controls global chunk options, e.g., knitr::opts_chunk$set(tidy = FALSE), which can be overridden by local chunk options. See all options at https://yihui.org/knitr/options/. Some frequently used options are:

  • eval: whether to evaluate the chunk
  • echo: whether to echo source code
  • results: 'markup', 'asis', 'hold', 'hide'
  • tidy: whether to reformat R code
  • cache: whether to cache results
  • fig.width, fig.height, out.width, out.height: device and output size of figures
  • include: whether to include the chunk results in output
  • child: path to child documents
  • engine: language name (R, python, …)

Functions

  • knit(): the main function in this package; knit input document and write output
  • purl(): extract R code from an input document
  • spin(): spin goat’s hair (an R script with roxygen comments) into wool (a literate programming document to be passed to knit())
  • stitch(): insert an R script into a template and compile the document
  • knit_hooks$set(): set or reset chunk and output hooks

Resources