rr-markdownquarto

Executing code embedded in a string in Quarto or R Markdown


I'm using an external JSON file to store the text that is being used in a Quarto document. This JSON file is being read in and then I'm using it to populate the text. I'd like to embed R code in the strings similar to what you can do with bare text in Quarto surrounded by tic marks.

Can this be done where the R code is executed

This is a JSON file being read in by Quarto (or R Markdown)

{
  "about": {
    "title": "The mean is `r mean(1:5)`"
  }
}

Here is code in a Quarto (or R Markdown) document

```{r}
info <- jsonlite::read_json("report_text.json")
```

This works but I am not using the JSON: The mean is `r mean(1:5)`

This does not work, this is what I want to do: `r info$about$title`


```{r, results='asis'}
# This does not work either
cat(info$about$title)
```

Solution

  • You can use knitr::knit_child to parse chunks of text

    ```{r, results='asis', echo=FALSE}
    cat(knitr::knit_child(text=info$about$title, quiet=TRUE))
    ```