Search code examples
rquarto

How can I reference derived values in Quarto documents before their calculation?


I frequently have to write .qmd Quarto documents with a section at the top that references variables defined further down in the document. For example, an abstract or an executive summary.

How can I reference the values before their definition in a code block below? In the example, I want the $20 in the Executive summary to have been referenced from the profit R variable not hard coded.

---
title: "Quatro results referencing"
format: html
---

# Executive Summary

- Business is great
- Profit is $20

# Methods

A complicated equation to calculate profit
```{r}
revenue <- 100 #dollars
expenses <- 80 #dollars

profit <- revenue - expenses
```{r}
This year, our profit is $`{r} profit`


Solution

  • ---
    title: "Quatro results referencing"
    format: html
    ---
    
    ```{r}
    #| echo: false
    #| label: code1
    revenue <- 100 #dollars
    expenses <- 80 #dollars
    
    profit <- revenue - expenses
    ```
    
    # Executive Summary
    
    - Business is great
    - Profit is $`{r} profit`
    
    # Methods
    
    A complicated equation to calculate profit
    ```{r}
    #| eval: false
    #| echo: true
    #| label: code1
    ```
    This year, our profit is $`{r} profit`
    

    Obviously, this can get tedious if many code blocks are needed to produce a value for the abstract.