首页 > 解决方案 > bookdown中如何使用Rscript命令行工具建书

问题描述

由于交叉引用功能,我使用bookdown而不是rmarkdown生成动态报告。我要生成多个报告,因此我起草了一个R脚本来循环调用bookdown:render_bookfor生成所有报告。不幸的是,它出错了。为简单起见,我构建了一个最小的示例:

要渲染的bookdown文件(另存为index.Rmd):

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

```{r test}
ext_var
```

build.R:_

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

使用以下命令时:Rscript build.R会产生以下错误信息:

$ 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.

然后我改变了我build.R的使用rmarkdown::render

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

不会有任何错误。所以我想可能有一些问题需要解决。

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  

还在存储库中提交了问题 #592rstudio/bookdown

标签: rr-markdownbookdown

解决方案


经过仔细研究bookdown::render_book功能,我找到了这个错误的真正原因。该函数设置了一个参数clean_envir,默认值为!interactive(). 这就是为什么bookdown使用命令行工具编织时环境变量会消失的原因。解决这个问题很简单,只需设置clean_envirFALSE,即

ext_var <- "test.html"
bookdown::render_book("index.Rmd", output_file = ext_var, clean_envir = FALSE)

然后它工作。


推荐阅读