Search code examples
rr-markdownbookdown

How to use Rscript command line tool to build a book in bookdown


Because of the cross-reference feature, I am using bookdown instead of rmarkdown to generate dynamic reports. I have more than one reports to generate, so I drafted an R script to call bookdown:render_book in a for loop to generate all the reports. Unfortunately, it errored. For simplicity, I build one minimal example:

The bookdown file to render (saved as index.Rmd):

---
title: "test"
output: html_document
---

```{r test}
ext_var
```

The build.R:

ext_var <- "test.html"
bookdown::render_book("index.Rmd", output_file = ext_var) # it will call `rmarkdown::render`.

When using following commands: Rscript build.R, it will generate the following error messages:

$ Rscript build.R
Error in rmarkdown::render(main, output_format, ..., clean = clean, envir = envir,  :
  'ext_var'
Calls: <Anonymous> -> render_cur_session -> <Anonymous>
Please delete _main.Rmd after you finish debugging the error.

Then I changed my build.R to use rmarkdown::render instead:

ext_var <- "test.html"
rmarkdown::render("index.Rmd", output_file = ext_var)

There won't be any error. So I guess there might be some issues to fix.

sessionInfo():

R version 3.5.0 (2018-04-23)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

Matrix products: default

locale:
[1] LC_COLLATE=Chinese (Simplified)_China.936  LC_CTYPE=Chinese (Simplified)_China.936   
[3] LC_MONETARY=Chinese (Simplified)_China.936 LC_NUMERIC=C                              
[5] LC_TIME=Chinese (Simplified)_China.936    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] RevoUtils_11.0.0     RevoUtilsMath_11.0.0

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.17    bookdown_0.7    digest_0.6.15   rprojroot_1.3-2 backports_1.1.2
 [6] magrittr_1.5    evaluate_0.10.1 stringi_1.1.7   rstudioapi_0.7  rmarkdown_1.10 
[11] tools_3.5.0     stringr_1.3.1   xfun_0.1        yaml_2.1.19     compiler_3.5.0 
[16] htmltools_0.3.6 knitr_1.20  

Also filed an issue #592 at rstudio/bookdown repository.


Solution

  • As you have discovered by yourself, the problem was caused by the default render_book(clean_envir = TRUE) in your case.

    However, please also note that bookdown::render_book() is not supposed to work with output formats other than those in the bookdown package. In other words, you should not expect the html_document format to work with render_book. If you need the feature of cross-references, please use those output formats of which the names end with 2 in the bookdown package (e.g., bookdown::html_document2), and these formats are designed to work with rmarkdown::render(). See Section 3.4 in the bookdown book for more information.