据我了解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'}
```
在全局环境中分配参数
使用此解决方案,参数由主文档中的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'}
```
获取子文档的参数
使用此解决方案,可以在每个子文档中控制参数。它是先前解决方案的变体。
在主文档中,使用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'}
```
使用(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}
```