Reactivity

September 22, 2024

What is Reactivity?


  • Reactivity in Shiny apps refers to the ability to update the user interface based on changes to input values.
  • R functions are used to update different parts of the app when they receive new values from the user.

Reactivity in Action


  • For instance, in a Shiny app, the renderPlot() function can update a plot based on a selected year, variable or country case.
  • Reactivity allows for rendering various elements like tables, images, or text without a full page reload.
  • The UI is dynamically updated, quickly generating new content based on the updated data.

Two Steps to Displaying Reactive Content


  • Add an R object to your user interface.
  • Tell Shiny how to build the object in the server function.
  • The object is reactive if it calls a widget value (an input).

Step 1: Add the Object to the UI

# Define UI for application that draws a scatter plot
ui <- fluidPage(

    # Application title
    titlePanel("Democracy and Development"),

    # Sidebar with a two dropdown menus
    sidebarLayout(
      sidebarPanel(
        selectInput(input = 'xcol', label = 'X Variable', choices = vars),
        selectInput(input = 'ycol', label = 'Y Variable', 
                    choices = vars, selected = vars[[6]])
      ),

        # Display the scatterplot 
        mainPanel(
           plotOutput("scatterplot")
        )
    )
)

Step 2: Build the Object in the Server Function

# Define server logic required to draw a scatter plot
server <- function(input, output, session) {
  
  # Render the plot
  output$scatterplot <- renderPlot({
    
    # ggplot call
    ggplot(dem_data, aes(x = get(input$xcol), y = get(input$ycol))) +
      geom_point(aes(color = region)) +
      geom_smooth(method = "loess") +
      scale_color_viridis_d(option = "plasma") +
      theme_minimal() +
      labs(
        x =  names(vars[which(vars == input$xcol)]), # select names in vars that
        y =  names(vars[which(vars == input$ycol)]), # match input selections
        caption = "Source: V-Dem Institute",
        color = "Region"
      )
  })
}

Reactive Because it is Calls a Widget Value (Server)

# Define server logic required to draw a scatter plot
server <- function(input, output, session) {
  
  # Render the plot
  output$scatterplot <- renderPlot({
    
    # ggplot call
    ggplot(dem_data, aes(x = get(input$xcol), y = get(input$ycol))) +
      geom_point(aes(color = region)) +
      geom_smooth(method = "loess") +
      scale_color_viridis_d(option = "plasma") +
      theme_minimal() +
      labs(
        x =  names(vars[which(vars == input$xcol)]), # select names in vars that
        y =  names(vars[which(vars == input$ycol)]), # match input selections
        caption = "Source: V-Dem Institute",
        color = "Region"
      )
  })
}

Reactive Because it is Calls a Widget Value (UI)

# Define UI for application that draws a scatter plot
ui <- fluidPage(

    # Application title
    titlePanel("Democracy and Development"),

    # Sidebar with a two dropdown menus
    sidebarLayout(
      sidebarPanel(
        selectInput(input = 'xcol', label = 'X Variable', choices = vars),
        selectInput(input = 'ycol', label = 'Y Variable', 
                    choices = vars, selected = vars[[6]])
      ),

        # Display the scatterplot 
        mainPanel(
           plotOutput("scatterplot")
        )
    )
)

Render Functions in Shiny


Render Function Creates
renderDataTable DataTable
renderImage Images (saved as a link to a source file)
renderPlot Plots
renderPrint Any printed output
renderTable Data frame, matrix, other table-like structures
renderText Character strings
renderUI A Shiny tag object or HTML

Output Functions in Shiny


Output Function Creates
dataTableOutput DataTable
htmlOutput Raw HTML
imageOutput Image
plotOutput Plot
tableOutput Table
textOutput Text
uiOutput Raw HTML
verbatimTextOutput Text

Limiting Reactivity

  • Reactive Expressions Control Reactivity: Limit what is re-executed during a reaction by using reactive expressions.
  • Definition and Behavior: A reactive expression in R leverages widget input to return a value, updating itself whenever the input widget changes.
  • Creating a Reactive Expression: Utilize the reactive function, similar to render* functions, which encapsulates an R expression within braces.

Example from this Week

Example from this Week


    # Download data from FRED with reactive function. 
    # Only updates when user selects new indicator
    fred_indicator <- reactive({
      fredr(series_id = input$indicator,
        observation_start = start_date,
        observation_end = end_date)
    })
  
    # Filter data according to chosen years 
    # Only updates when user selects new data range
    fred_data <- reactive({
      fred_indicator() |>
      filter(between(date, input$range[1],input$range[2])) 
   })

Your Turn!


  • Do the prework, getting set up with fredr and other relevant packages
  • Create a NEW project folder
  • Save your helper script in a subfolder
  • Start on your app.R file
  • Four parts:
    • setup
    • UI
    • Server
    • Call to Shiny App
  • Extend the app by incorporating new indicators