Reactive variables

Case Studies: Building Web Applications with Shiny in R

Dean Attali

Shiny Consultant

Code duplication

data <- gapminder
data <- subset(
    data,
    lifeExp >= input$life[1] & lifeExp <= input$life[2]
)
if (input$continent != "All") {
    data <- subset(
        data,
        continent == input$continent
   )
}
  • Duplicated 3 times
    1. renderTable()
    2. renderPlot()
    3. downloadHandler()
Case Studies: Building Web Applications with Shiny in R

Reactive variables reduce code duplication

  • Duplicated code ⇒ multiple places to maintain
    • When code needs updating
    • When bugs need fixing
  • Easy to forget one instance, leading to bugs
  • Use reactive() variables instead of code duplication
Case Studies: Building Web Applications with Shiny in R

Reactive variables

output$my_table <- renderTable({
    data <- gapminder
    data <- subset(
        data,
        lifeExp >= input$life[1] & lifeExp <= input$life[2]
    )
})
my_data <- reactive({

data <- gapminder data <- subset( data, lifeExp >= input$life[1] & lifeExp <= input$life[2] )
})
output$my_table <- renderTable({ my_data() })
Case Studies: Building Web Applications with Shiny in R

Reactive variables caching

  • Reactive variables cache their values
  • Remember their own value
  • Do not run again if dependencies didn't change
Case Studies: Building Web Applications with Shiny in R

Reactive variables caching

  output$table <- renderTable({
      fit_model(input$num)
  })

  output$plot <- renderPlot({
      ggplot(
        fit_model(input$num), ...)
  })
  • fit_model() takes 5s
  • fit_model() called twice = 10s
x <- reactive({
    fit_model(input$num)
})

output$table <- renderTable({ x() })
output$plot <- renderPlot({ ggplot(x(), ...) })
  • x() called twice, code inside x runs once
  • fit_model() called once = 5s
Case Studies: Building Web Applications with Shiny in R

Reactive variables are lazy

  • Lazy variable = not calculated until value is needed

    x <- reactive({
        fit_model(input$num)
    })
    
    output$download <- downloadHandler(
        filename = "x.csv",
        content = function(file) {
            write.csv(x(), file)
        }
    )
    
  • x() only runs when download is requested, not every time input$num changes

Case Studies: Building Web Applications with Shiny in R

Let's practice!

Case Studies: Building Web Applications with Shiny in R

Preparing Video For Download...