Conditionally include chapters in Bookdown
Asked Answered
D

2

8

Suppose i have a main R-Markdown file called index.Rmd and another R-Markdown file called child.Rmd. If i want to include the R-Markdown file child.Rmd based on the condition params$value1 > params$value2, i can add the following code to the file index.Rmd

condition <- params$value1 > params$value2
filepathToChild <- "/home/user/child.Rmd"
```{r conditional_print, 
child=filepathToChild , eval = condition
}
```

Using bookdown, i can create a file called _bookdown.yml with the following content to include the content of the file child.Rmd after the content of the file index.Rmd:

rmd_files: ["index.Rmd", "child.Rmd"]

How can i include the content of the file child.Rmd in bookdown based on the condition params$value1 > params$value2?

Doughy answered 14/3, 2019 at 14:15 Comment(0)
H
3

I can't think of a solution to do it in yml, but you could create that yml-file programmatically and combine it with the rendering process.

Just create a simple script to generate the .yml-file and do the rendering:

# 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')

Then you could compile the book from command line:

Rscript compile_my_book.R value1 value2

(or create a makefile or something similar to run multiple things for you)

So running Rscript compile_my_book.R 1 2 does not add the conditional files, but Rscript compile_my_book.R 2 1 does it.

It's a bit hacky, but I'm using similar workflows to create long .xml-config files for some web apps I use, by reading in data from several sources, checking some conditions and creating the config file.

Houseboat answered 7/6, 2020 at 10:47 Comment(0)
S
1

Another way is simply to put all your chapter's code in another Rmd(child2.Rmd), to call it in child.Rmd and to add an eval condition :

```{r, child= 'child.Rmd',eval=params$value1 > params$value2}
```

And you change nothing to your yml.

Stealing answered 30/5, 2022 at 15:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.