有条件地在 Bookdown 中包含章节

pee*_*eer 6 r r-markdown bookdown

假设我有一个名为 index.Rmd 的主 R-Markdown 文件和另一个名为 child.Rmd 的 R-Markdown 文件。如果我想根据条件包含 R-Markdown 文件 child.Rmd params$value1 > params$value2,我可以将以下代码添加到文件 index.Rmd

condition <- params$value1 > params$value2
filepathToChild <- "/home/user/child.Rmd"
```{r conditional_print, 
child=filepathToChild , eval = condition
}
```
Run Code Online (Sandbox Code Playgroud)

使用 bookdown,我可以创建一个名为 _bookdown.yml 的文件,其中包含以下内容,以在文件 index.Rmd 的内容之后包含文件 child.Rmd 的内容:

rmd_files: ["index.Rmd", "child.Rmd"]
Run Code Online (Sandbox Code Playgroud)

如何根据条件在 bookdown 中包含文件 child.Rmd 的内容params$value1 > params$value2

小智 3

我想不出在 yml 中执行此操作的解决方案,但您可以以编程方式创建该 yml 文件并将其与渲染过程结合起来。

只需创建一个简单的脚本来生成 .yml 文件并进行渲染:

# compile_my_book.R

# get the parameters
param1 <- commandArgs(trailingOnly = TRUE)[1]
param2 <- commandArgs(trailingOnly = TRUE)[2]

# just some dummy yml from bookdown examples
my_yml <- paste0(
"book_filename: 'my-book.Rmd'
before_chapter_script: ['script1.R', 'script2.R']
output_dir: 'book-output'
clean: ['my-book.bbl', 'R-packages.bib']"
)

# list the files
# (here you could also use list.files to get them automatically, sorting them etc.)
my_files <- c("chapter01.Rmd", "chapter02.Rmd", "References.Rmd")

# add your conditional files
if (param1 > param2) my_files <- c(my_files, "conditional.Rmd")

# create the _bookdown.yml
cat(my_yml,
    "\nrmd_files: ['", paste0(my_files, collapse = "', '"), "']",
    file = "_bookdown.yml", sep = "")

# render your book with the arguments you want (excluding the values you want to check for)
bookdown::render_book('index.Rmd', 'bookdown::gitbook')
Run Code Online (Sandbox Code Playgroud)

然后你可以从命令行编译这本书:

Rscript compile_my_book.R value1 value2
Run Code Online (Sandbox Code Playgroud)

(或者创建一个 makefile 或类似的东西来为你运行多个东西)

所以运行Rscript compile_my_book.R 1 2不会添加条件文件,而是Rscript compile_my_book.R 2 1添加条件文件。

这有点 hacky,但我使用类似的工作流程为我使用的一些 Web 应用程序创建长 .xml-config 文件,方法是从多个源读取数据,检查一些条件并创建配置文件。