Chapter 15 Other Languages

Besides the R language, many other languages are supported in R Markdown through the knitr package. The language name is indicated by the first word in the curly braces after the three opening backticks. For example, the little r in ```{r} indicates that the code chunk contains R code, and ```{python} is a Python code chunk. In this chapter, we show a few languages that you may not be familiar with.

In knitr, each language is supported through a language engine. Language engines are essentially functions that take the source code and options of a chunk as the input, and return a character string as the output. They are managed through the object knitr::knit_engines. You may check the existing engines via:

  1. names(knitr::knit_engines$get())
  1. ## [1] "awk" "bash" "coffee" "gawk"
  2. ## [5] "groovy" "haskell" "lein" "mysql"
  3. ## [9] "node" "octave" "perl" "psql"
  4. ## [13] "Rscript" "ruby" "sas" "scala"
  5. ## [17] "sed" "sh" "stata" "zsh"
  6. ## [21] "highlight" "Rcpp" "tikz" "dot"
  7. ## [25] "c" "cc" "fortran" "fortran95"
  8. ## [29] "asy" "cat" "asis" "stan"
  9. ## [33] "block" "block2" "js" "css"
  10. ## [37] "sql" "go" "python" "julia"
  11. ## [41] "sass" "scss"

At the moment, most code chunks of non-R languages are executed independently. For example, all bash code chunks in the same document are executed separately in their own sessions, so a later bash code chunk cannot use variables created in a previous bash chunk, and the changed working directory (via cd) will not be persistent across different bash chunks. Only R, Python, and Julia code chunks are executed in the same session. Please note that all R code chunks are executed in the same R session, and all Python code chunks are executed in the same Python session, etc. The R session and the Python session are two different sessions, but it is possible to access or manipulate objects of one session from another session (see Section 15.2).

Section 2.7 of the R Markdown Definitive Guide (Xie, Allaire, and Grolemund 2018) shows examples of using Python, Shell, SQL, Rcpp, Stan, JavaScript, CSS, Julia, C, and Fortran code in R Markdown. In this chapter, we will show more language engines, and you may find more examples in the repository at https://github.com/yihui/knitr-examples (look for filenames that contain the word “engine”).

First, let’s reveal how a language engine works by registering a custom language engine.

References

Xie, Yihui, J. J. Allaire, and Garrett Grolemund. 2018. R Markdown: The Definitive Guide. Boca Raton, Florida: Chapman; Hall/CRC. https://bookdown.org/yihui/rmarkdown.