B.1 knitr

The knitr package was designed based on the idea of “Literate Programming” (Knuth 1984), which allows you to intermingle program code with text in a source document. When knitr compiles a document, the program code (in code chunks) will be extracted and executed, and the program output will be displayed together with the original text in the output document. We have introduced the basic syntax in Section 2.3.

R Markdown is not the only source format that knitr supports. The basic idea can be applied to other computing and authoring languages. For example, knitr also supports the combination of R and LaTeX (*.Rnw documents), and R + HTML (*.Rhtml), etc. You can use other computing languages with knitr as well, such as C++, Python, SQL, and so on. Below is a simple example and you can see http://rmarkdown.rstudio.com/authoring_knitr_engines.html for more.

x = 'Hello, Python World!'
print(x.split(' '))

Python users may be familiar with IPython or Jupyter Notebooks (https://jupyter.org). In fact, R Markdown can also be used as notebooks, and has some additional benefits; see this blog post for more information: https://blog.rstudio.org/2016/10/05/r-notebooks/.

If you want to show a literal chunk in your document, you can add an inline expression that generates an empty string (`r ''`) before the chunk header, and indent the code chunk by four spaces,13 e.g.,

    `r ''````{r}
    # a literal code chunk

After the document is compiled, the inline expression will disappear and you will see:

# a literal code chunk

Normally you do not need to call knitr functions directly when compiling a document, since rmarkdown will call knitr. If you do want to compile a source document without further converting it to other formats, you may use the knitr::knit() function.


Knuth, Donald E. 1984. “Literate Programming.” The Computer Journal 27 (2). British Computer Society: 97–111.

  1. Follow the four-space rule if the literal code chunk is to be displayed in other environments such as a list: http://pandoc.org/MANUAL.html#the-four-space-rule