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:
---title: Use `purl()` to extract R code---The function `knitr::purl()` extracts R code chunks froma **knitr** document and save the code to an R script.Below is a simple chunk:```{r, simple, echo=TRUE}1 + 1```Inline R expressions like `r 2 * pi` are ignored by default.If you do not want certain code chunks to be extracted,you can set the chunk option `purl = FALSE`, e.g.,```{r, ignored, purl=FALSE}x = rnorm(1000)```
If we call knitr::purl("purl.Rmd"), it generates the following R script (with the filename purl.R by default):
## ----simple, echo=TRUE-------------------------------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:
If you want to retain all the text, you may use the argument documentation = 2, which generates the R script below:
#' ---#' title: Use `purl()` to extract R code#' ---#'#' The function `knitr::purl()` extracts R code chunks from#' a **knitr** document and save the code to an R script.#'#' Below is a simple chunk:#'## ----simple, echo=TRUE-------------------------------1 + 1#'#' Inline R expressions like `r 2 * pi` are ignored by default.#'#' If you do not want certain code chunks to be extracted,#' you can set the chunk option `purl = FALSE`, e.g.,#'
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().
