3.4 Convert R Markdown to R script

When you want to extract all R code from an R Markdown document, you can call the function knitr::purl(). Below is a simple Rmd example with the filename purl.Rmd:

  1. ---
  2. title: Use `purl()` to extract R code
  3. ---
  4. The function `knitr::purl()` extracts R code chunks from
  5. a **knitr** document and save the code to an R script.
  6. Below is a simple chunk:
  7. ```{r, simple, echo=TRUE}
  8. 1 + 1
  9. ```
  10. Inline R expressions like `r 2 * pi` are ignored by default.
  11. If you do not want certain code chunks to be extracted,
  12. you can set the chunk option `purl = FALSE`, e.g.,
  13. ```{r, ignored, purl=FALSE}
  14. x = rnorm(1000)
  15. ```

If we call knitr::purl("purl.Rmd"), it generates the following R script (with the filename purl.R by default):

  1. ## ---- simple, echo=TRUE------------------------------
  2. 1 + 1

The above R script contains the chunk options in a comment. If you want pure R code, you may call knitr::purl() with the argument documentation = 0, which will generate the R script below:

  1. 1 + 1

If you want to retain all the text, you may use the argument documentation = 2, which generates the R script below:

  1. #' ---
  2. #' title: Use `purl()` to extract R code
  3. #' ---
  4. #'
  5. #' The function `knitr::purl()` extracts R code chunks from
  6. #' a **knitr** document and save the code to an R script.
  7. #'
  8. #' Below is a simple chunk:
  9. #'
  10. ## ---- simple, echo=TRUE------------------------------
  11. 1 + 1
  12. #'
  13. #' Inline R expressions like `r 2 * pi` are ignored by default.
  14. #'
  15. #' If you do not want certain code chunks to be extracted,
  16. #' you can set the chunk option `purl = FALSE`, e.g.,
  17. #'

Note that code chunks with the option purl = FALSE will be excluded in the R script.

Inline R expressions are ignored by default. If you want to include them in the R script, you need to set the global R option options(knitr.purl.inline = TRUE) before calling knitr::purl().