如何通过 R 中的参数化 Quarto 文档将 Quarto R 包的逻辑参数传递到 knitr 块选项

Mic*_*Luu 2 r quarto

我在下面提供了一个最小的可重现示例。我目前正在尝试使用 R quarto 包将逻辑参数传递到 Quarto 块选项中。

下面是四开文档,我在其中创建了 2 个参数 、show_codeshow_plot

---
title: "Untitled"
format: html
params:
  show_code: TRUE
  show_plot: TRUE
---

```{r, echo=params$show_code}
summary(cars)
```

```{r, include=params$show_plot}
plot(pressure)
```
Run Code Online (Sandbox Code Playgroud)

该文档将通过 R studio 中的渲染按钮正确渲染。

但是,当尝试通过 R quarto 包中的函数渲染此文档时quarto_render(),将会失败。

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)
)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

看起来,控制台中的块 1 和块 2 都yes传递了一个字符,而不是逻辑TRUE或。FALSE

如何通过 正确地将逻辑字符传递给参数化的四开报表块选项quarto_render()

sha*_*fee 5

选项 1(在块头中使用块选项)

我们可以在 chunk 选项中使用逻辑语句(就像我们在 r-markdown 中所做的那样)。


参数化_报告.qmd

---
title: "Using Parameters"
format: html
params:
  show_code: "yes"
  show_plot: "yes"
---

```{r, echo=(params$show_code == "yes")}
summary(cars)
```

```{r, include=(params$show_plot == "yes")}
plot(pressure)
```
Run Code Online (Sandbox Code Playgroud)

然后从 r-console/rscript 文件中,我们quarto_render使用 params"yes"或来调用"no"

quarto::quarto_render(
  input = 'parameterized_report.qmd',
  output_format = 'html',
  output_file = 'qmd_document_with_code.html',
  execute_params = list(show_plot = "yes",
                        show_code = "no")
)

Run Code Online (Sandbox Code Playgroud)

仅包含代码输出和绘图的 html 输出


选项 2(使用 YAML 语法块选项)

请注意,上面我们在块头中使用了 chunk 选项,该选项与 knitr 引擎配合良好,但 quarto 更喜欢基于注释的 yaml 语法(即使用#|)。根据四开文档

请注意,如果您愿意,仍然可以在第一行包含块选项(例如 ```{r, echo = FALSE})。也就是说,我们建议使用基于注释的语法来使文档在执行引擎之间更加可移植和一致。这种方式包含的块选项使用 YAML 语法而不是 R 语法,以与 YAML 前面提供的选项保持一致。不过,您仍然可以使用 R 代码作为选项值,方法是在它们前面加上!expr

因此,按照四开的首选方式,我们可以使用这样的参数,


参数化_报告.qmd

---
title: "Using Parameters"
format: html
params:
  show_code: "false"
  show_plot: "false"
---


```{r}
#| echo: !expr params$show_code

summary(cars)
```

```{r}
#| include: !expr params$show_plot

plot(pressure)
```
Run Code Online (Sandbox Code Playgroud)

quarto_render然后与"true"或 一起使用"false"

quarto::quarto_render(
  input = 'parameterized_report.qmd',
  output_format = 'html',
  output_file = 'qmd_document_with_code.html',
  execute_params = list(show_plot = "true",
                        show_code = "true")
)

Run Code Online (Sandbox Code Playgroud)

最后,注意两点,

  • 在这里,我们使用了"true"or "false",因为echo, include,在此基于注释的语法中eval采用值true/false而不是TRUE/ 。FALSE

  • 此外,由于knitr 1.35,knitr 引擎也支持这种基于注释的语法。请参阅knitr v1.35 到 v1.37 的新闻:块选项的替代语法