R Expressions in Quarto Yaml Header

Does Quarto support R expressions within the YAML header?

I have a quarto QMD file that has the following yaml:

---
format:
  docx:
    reference-doc: !expr system.file('reference.docx', package = 'custom_package')
---

This throws a YAML parsing error : Error in $: parsing Text failed, expected String, but encountered Object which suggests that the expression isn't being evaluated and substitute with a string.

I've tried other methods such as the ones discussed here but haven't had any success getting this to work properly. IIRC you could get expressions like this to work in RMarkdown but that may not be the case in Quarto.

After a bit of testing, I've found that this works in quarto:

title: "`r system.file('reference.docx', package = 'custom_package')`"

system.file evaluates correctly and the path is shown in the title.

But this does not.

title: "A title"
format:
  docx:
    reference-doc: "`r system.file('reference.docx', package = 'custom_package')`"

So, I imagine this is just not supported in either quarto or rmarkdown.

1 Like

You can't use R expression in YAML header with Quarto. This is a matter of when a YAML option is needed and used.

Quarto will only run R for evaluating your computation chunks. Everything else will be done without R (or Python). Especially, YAML header is not read using a R parser like yaml parser which the package that support !expr to evaluate the text as an R expression.

So you can't really do that with Quarto. It could be working in some edgecase like you did with title, but it is just a side effect of title field not being used elsewhere by quarto in simple document and so knitr would replace the YAML field and Pandoc would read it correctly. However, in website context, this would probably not work.

So unfortunately you can't do exactly the same in Quarto than in R Markdown, because

  • R Markdown is all R for pre processing, knitting post processing
  • but Quarto is R only for evaluating R chunks with knitr. Otherwise, pre processing and post processing is not involving R. So R expression means nothing.

Hope it helps understand the why.

if you need variables in Quarto , have a look at Quarto - Variables

Yeah this makes a lot of sense. Thank you for the conformation!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.