如何从 RMarkdown (.Rmd) 文件中提取所有代码?

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

如何从 RMarkdown (.Rmd) 文件中提取所有代码(块)并将它们转储到普通 R 脚本中?

基本上我想做 中描述的补充操作,它使用块选项来提取 Rmd 的文本(即非代码)部分。

具体来说,我想从如下所示的 Rmd 文件开始

---
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.

只包含上述代码部分的R脚本,如下:

knitr::opts_chunk$set(echo = TRUE)

a = 1
print(a)
summary(cars)

plot(pressure)

您可以使用 knitr::purl,参见 convert Markdown to R script :

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

给出 Report.R:

knitr::opts_chunk$set(echo = TRUE)

a = 1
print(a)
summary(cars)

plot(pressure)

另一种方法是在 Rmd:

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

然后在编织时生成R脚本。您可以使用块选项 purl = FALSE.

排除一些块