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.

```{python}
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 wrap the code chunk in four backticks,14 e.g.,

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

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

```{r}
# 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.

References

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

  1. Follow the indenting rule if the literal code chunk is to be displayed in other environments such as a list: https://pandoc.org/MANUAL.html#block-content-in-list-items↩︎