Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

r-markdown

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)
like image 646
Anil Avatar asked Dec 07 '25 04:12

Anil


2 Answers

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)
like image 124
Waldi Avatar answered Dec 08 '25 16:12

Waldi


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.

like image 45
Stéphane Laurent Avatar answered Dec 08 '25 17:12

Stéphane Laurent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!