Home > OS >  How to extract all code from an RMarkdown (.Rmd) file?
How to extract all code from an RMarkdown (.Rmd) file?

Time:02-20

How can I extract all the code (chunks) from an RMarkdown (.Rmd) file and dump them into a plain R script?

Basically I wanted to do the complementary operation described in this question, which uses chunk options to pull out just the text (i.e. non-code) portion of the Rmd.

So concretely I would want to go from an Rmd file like the following

---
title: "My RMarkdown Report"
author: "John Appleseed"
date: "19/02/2022"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## R Markdown

Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents.   
For more details on using R Markdown see <http://rmarkdown.rstudio.com>.  

Some text description here. 

```{r cars}
a = 1
print(a)
summary(cars)
```

## Including Plots

You can also embed plots, for example:

```{r pressure, echo=FALSE}
plot(pressure)
```

Some more comments here.

To an R script containing just the code portions of the above, as the following:

knitr::opts_chunk$set(echo = TRUE)

a = 1
print(a)
summary(cars)

plot(pressure)

CodePudding user response:

You could use knitr::purl, see convert Markdown to R script :

knitr::purl(input = "Report.Rmd", output = "Report.R",documentation = 0)

gives Report.R:

knitr::opts_chunk$set(echo = TRUE)

a = 1
print(a)
summary(cars)

plot(pressure)

CodePudding user response:

Another way is to set the purl hook in your Rmd:

```{r setup, include=FALSE}
knitr::knit_hooks$set(purl = knitr::hook_purl)
knitr::opts_chunk$set(echo = TRUE)
```

Then the R script is generated when you knit. You can exclude some chunks with the chunk option purl = FALSE.

  • Related