Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally include chapters in Bookdown

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?

like image 626
peer Avatar asked Mar 14 '19 14:03

peer


1 Answers

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.

like image 147
ek-g Avatar answered Oct 17 '22 06:10

ek-g