如何通过quarto_render()传递逻辑参数至Quarto文档的knitr块选项
解决Quarto渲染时逻辑参数传入knitr块选项的问题
问题根源在于:使用quarto_render()的execute_params传递逻辑参数时,Quarto会自动将布尔值转换为字符串"yes"或"no",但knitr的块选项(如echo、include)要求的是布尔类型(TRUE/FALSE),直接引用params$show_code会导致类型不匹配,从而引发渲染异常。
解决方案:显式转换参数类型
在knitr块选项中,将传入的字符串参数转换为布尔值,有两种可行方式:
方式一:使用as.logical()转换
修改Quarto文档的块选项如下:
--- title: "Untitled" format: html params: show_code: TRUE show_plot: TRUE --- ```{r, echo=as.logical(params$show_code)} summary(cars)
plot(pressure)
#### 方式二:直接判断参数值 通过判断参数是否等于`"yes"`来生成布尔值: ```qmd --- title: "Untitled" format: html params: show_code: TRUE show_plot: TRUE --- ```{r, echo=params$show_code == "yes"} summary(cars)
plot(pressure)
### 渲染代码无需修改 你的R渲染代码保持原样即可: ```r library(quarto) quarto::quarto_render( input = 'qmd_document.qmd', output_format = 'html', output_file = 'qmd_document_with_code.html', execute_params = list(show_plot = TRUE, show_code = TRUE) )
这样修改后,无论是通过RStudio的渲染按钮,还是使用quarto_render()函数,参数都能正确被解析为knitr所需的布尔值,解决类型不匹配导致的渲染失败问题。
内容的提问来源于stack exchange,提问作者Michael Luu
相关产品推荐
相关产品推荐

