Rmarkdown 子文档没有检测到它们的 `params`

mat*_*fee 5 r knitr r-markdown

我有一个主 Rmarkdown 文档,我使用knitr'schild选项将我的各个章节包含在其中。每章都在自己的 YAML 中使用rmarkdown 参数。每章单独编译得很好,但是当放入这个主文档时,我得到错误

object: 'params' not found
Run Code Online (Sandbox Code Playgroud)

我相信是因为当孩子被编织时,knitr 不会读取 YAML 中的参数(这是一个 rmarkdown 功能,而不是 knitr 功能)。

有什么方法可以让 knitr 可以使用这些吗?是否有“rmarkdown”方式来放入子文档?

---
title: My thesis
---

blah blah.

# Introduction

```{r child='01-introduction.rmd'}
```

# Mathematical background

```{r child='02-mathsy-maths.rmd'}
```
Run Code Online (Sandbox Code Playgroud)

例子 01-introduction.rmd

---
title: Introduction
params:
    dataset: ABC
---
Run Code Online (Sandbox Code Playgroud)

RLe*_*sur 7

据我了解knitr,当您编织子文档时,该文档将在父文档的上下文(即环境)中进行评估。

所以,我看到了 4 个解决方案。

在主文档中设置参数

通过此解决方案,参数被控制在YAML主文档的 front-matter 内。我认为这是自然的解决方案。

---
title: My thesis
params:
  dataset: ABC
---

blah blah.

# Introduction

```{r child='01-introduction.rmd'}
```

# Mathematical background

```{r child='02-mathsy-maths.rmd'}
```
Run Code Online (Sandbox Code Playgroud)

在全局环境中分配参数

R使用此解决方案,参数由主文档内的代码控制。

---
title: My thesis
---

blah blah.

# Introduction
```{r set-params, include=FALSE}
params <- list(dataset = "ABC")
```

```{r child='01-introduction.rmd'}
```

# Mathematical background

```{r child='02-mathsy-maths.rmd'}
```
Run Code Online (Sandbox Code Playgroud)

检索子文档的参数

通过此解决方案,参数在每个子文档内进行控制。它是先前解决方案的变体。
在主文档中,使用全局环境读取子文档的参数knitr::knit_params(),然后在全局环境中对其进行分配。

---
title: My thesis
---

blah blah.

```{r def-assign-params, include=FALSE}
assign_params <- function(file) {
  text <- readLines(file)
  knit_params <- knitr::knit_params(text)
  params <<- purrr::map(knit_params, "value")
}
```

# Introduction

```{r, include=FALSE}
assign_params('01-introduction.rmd')
```

```{r child='01-introduction.rmd'}
```

# Mathematical background

```{r child='02-mathsy-maths.rmd'}
```
Run Code Online (Sandbox Code Playgroud)

使用(hacky)钩子临时分配参数

在这里,我为新的use.params块选项定义了一个钩子:此解决方案扩展了前一个解决方案。当use.params=TRUE使用时,该钩子针对子文档的每个块运行。请注意,使用此解决方案时,您不能在内联代码中
使用。params

---
title: "Main document"
---

```{r hook-def, include=FALSE}
params_cache <- new.env(parent = emptyenv())

knitr::knit_hooks$set(use.params = function(before, options, envir) {
  if (before && options$use.params) {
    if (exists("params", envir = envir)) {
      params_cache$params <- envir$params
    }
    text <- readLines(knitr::current_input(dir = TRUE))
    knit_params <- knitr::knit_params(text)
    envir$params <- purrr::map(knit_params, "value")
  }
  if (!before && options$use.params) {
    if (exists("params", envir = params_cache)) {
      envir$params <- params_cache$params
      rm("params", envir = params_cache)
    } else {
      rm("params", envir = envir)
    }
  }
})
```

blah blah.

# Introduction

```{r child='01-introduction.rmd', use.params=TRUE}
```

# Mathematical background

```{r child='02-mathsy-maths.rmd', use.params=TRUE}
```
Run Code Online (Sandbox Code Playgroud)