Search code examples
rshinyquarto

Load packages at one place for multiple shiny apps in Quarto


I have a Quarto HTML document with multiple shiny apps. I prefer to have all the packages I use in the document to have in one chunk at the top of the document. The problem is I have multiple shiny apps so it needs to have these packages in each server chunk of the shiny app which is not ideal. Here is a reproducible example:

---
title: "Old Faithful"
format: html
server: shiny
---

```{r}
#| echo: false
#| warning: false
#| message: false
library(dplyr)
library(ggplot2)
```

```{r}
sliderInput("bins", "Number of bins:", 
            min = 1, max = 50, value = 30)
plotOutput("distPlot")
```

```{r}
#| context: server
output$distPlot <- renderPlot({
  ggplot(faithful, aes(x = waiting)) +
    geom_histogram(bins = input$bins)
})
```

Output:

enter image description here

As you can see it doesn't work because the packages are not loaded on the server. But in this example, I have one app, but when having multiple you should add these packages every time. So I was wondering if anyone knows a way to load the packages in one place when having multiple shiny apps in a Quarto document?


Solution

  • I just found that you could simply add #| context: server to the chunk with all packages like this:

    ---
    title: "Old Faithful"
    format: html
    server: shiny
    ---
    
    ```{r}
    #| echo: false
    #| warning: false
    #| message: false
    #| context: server
    library(dplyr)
    library(ggplot2)
    ```
    
    ```{r}
    sliderInput("bins", "Number of bins:", 
                min = 1, max = 50, value = 30)
    plotOutput("distPlot")
    ```
    
    ```{r}
    #| context: server
    output$distPlot <- renderPlot({
      ggplot(faithful, aes(x = waiting)) +
        geom_histogram(bins = input$bins)
    })
    ```
    

    Output:

    enter image description here