将代码块从一个 Rmarkdown 文档插入另一个文档

Inserting code chunks from one Rmarkdown document into another

我一直在 运行 一些小型 R 教程/研讨会,为此我将 'challenge scripts' 保存在 Rmarkdown 文档中。这些包含自由文本和 R-code 块。一些代码块是预先填充的(例如,设置数据集供以后使用),而一些代码块供与会者在研讨会期间 fill-in 编码。

对于每个挑战脚本,我都有一个解决方案脚本。后者包含前者的所有自由文本,但任何 challenge-blocks 都已填写(有一个解决方案工作簿示例 here)。

我真的不想保留同一个文件(挑战和解决方案工作簿)的两个密切相关的副本。所以我想知道是否有一种简单的方法可以从我的解决方案脚本(或来自 challenge-script 的解决方案脚本和仅包含解决方案块的 R-script 构建我的挑战脚本。

例如,有没有一种简单的方法可以用另一个 rmarkdown 文件中的 correspondingly-named 代码块替换一个 Rmarkdown 文件中所有名为 code-blocks 的代码块?

也就是说,如果我有

challenge.Rmd

HEADER

简介

今天我们将学习如何在 R

中对 pseudo-random 数字进行采样
```{r challenge_1}
# Challenge 1: Make a histogram of 100 randomly-sampled 
# normally-distributed values
```

哇哇哇

END_OF_FILE

solutions.Rmd

HEADER

```{r challenge_1}
# Challenge 1: Make a histogram of 100 randomly-sampled 
# normally-distributed values
hist(rnorm(100))
```

END_OF_FILE

如何将 challenge.Rmd 中的 challenge_1 替换为 solutions.Rmd 中的 challenge_1

祝一切顺利

这是一种方法:

challenge.Rmd

---
output: html_document
---

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

```{r child="solution.Rmd", eval=show_solution}
```

Today we're going to learn about sampling pseudo-random numbers in R

```{r challenge_1}
# Challenge 1: Make a histogram of 100 randomly-sampled 
# normally-distributed values
```

```{r challenge_1_s, eval=show_solution, echo=show_solution}
```


```{r challenge_2}
# Challenge 2: Make a histogram of 100 randomly-sampled 
# uniform-distributed values
```

```{r challenge_2_s, eval=show_solution, echo=show_solution}
```

solution.Rmd

```{r challenge_1_s, eval=FALSE, echo=FALSE}
# Challenge 1: Make a histogram of 100 randomly-sampled 
# normally-distributed values
hist(rnorm(100))
```

```{r challenge_2_s, eval=FALSE, echo=FALSE}
# Challenge 2: Make a histogram of 100 randomly-sampled 
# uniform-distributed values
hist(runif(100))
```

使用 show_solution 参数,您可以在 rmarkdown 中包含或排除解决方案。参与者无法为 show_solution = TRUE 编写文档,除非他们有 solution.Rmd。对于 show_solution = FALSE 没有问题,并且编译得很好。