Home > Net >  How to pass logical parameters with the Quarto R package to the knitr chunk options via a parameteri
How to pass logical parameters with the Quarto R package to the knitr chunk options via a parameteri

Time:09-02

I've provided a minimal reproducible example below. I'm currently trying to use the R quarto package to pass a logical parameter into the Quarto chunk options.

Below is the quarto document, where I created 2 parameters, show_code, and show_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)
```

This document would render properly via the render button in R studio.

However, when trying to render this document via the quarto_render() function from the R quarto package, this would fail.

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)
)

enter image description here

It appears that a character yes is passed instead of the logical TRUE or FALSE to both Chunk 1 and Chunk 2 in the console.

How do I properly pass the logical characters to a parameterized Quarto report chunk options via quarto_render()?

CodePudding user response:

Option 1 (Using chunk options in chunk header)

We can use logical statement in chunk option (html output with only code output and plot


Option 2 (Using YAML syntax chunk option)

Note that, above we have used the chunk option in the chunk header which works fine with knitr engine, but quarto prefers comment-based yaml syntax (i.e. using #|). As per the quarto documentation

Note that if you prefer it is still possible to include chunk options on the first line (e.g. ```{r, echo = FALSE}). That said, we recommend using the comment-based syntax to make documents more portable and consistent across execution engines. Chunk options included this way use YAML syntax rather than R syntax for consistency with options provided in YAML front matter. You can still however use R code for option values by prefacing them with !expr

So following the quarto preferred way, we can use parameters like this,


parameterized_report.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)
```

then use quarto_render with "true" or "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")
)

Lastly, note two things,

  • Related