rquarto

Is there a way to render dynamic headings in Quarto using R?


I have several Quarto documents whose headings change dynamically. So far, I have manually entered them, but it needs to be reproducible with different datasets.

Say I have this set of model numbers as a column in a tibble.

Model <- sample(1:1000)
models <- tibble(Model = Model[1:10])

I want to dynamically create a Header 2 sized header using the values in the models$Model column. Here is what I've tried in a code chunk:

{r, echo=FALSE, results='asis'}

header <- paste0('Model #', models$Model[[1]])

cat(paste0('##', header))

Unfortunately, this only outputs a normal text with two ## in front of it, like so:

##Model #687

Is there a way to render this as a header? Thank you!!


Solution

  • You have to add a space to separate the ## from the title, e.g. you can use paste instead of paste0 but actually neither is required, i.e. you can use cat without paste(0):

    ---
    title: "Untitled"
    format: html
    editor: visual
    ---
    
    ```{r}
    set.seed(123)
    
    Model <- sample(1:1000)
    models <- data.frame(Model = Model[1:10])
    ```
    
    ```{r , echo=FALSE, results='asis'}
    header <- paste0('Model #', models$Model[[1]])
    
    cat(paste('##', header))
    ```
    
    ```{r , echo=FALSE, results='asis'}
    header <- paste0('Model #', models$Model[[1]])
    
    cat('##', header)
    ```
    

    enter image description here