trippy
trippy

Reputation: 150

R Shiny - How to update a dependent reactive selectInput before updating dependent reactive plot

App Structure

I have a Shiny app with the typical sidebar panel + mainpanel structure.

Problem

When the user chooses a new dataset in selectInput #1, both the selectInput #2 (available variables) and the plot will need to update. I want the selectInput #2 to update first, and then the plot. However, it seems the plot always proceeds to update before the 2nd selectInput has a chance to update. This results in the plot trying to render an invalid plot -- i.e., tries to render a plot of an mtcars variable using the iris dataset, or vice versa.

Is there a way to prioritize the reactive update of the selectInput #2 to occur before the reactive update of the renderPlot?

Notes

library(shiny)
library(ggplot2)
library(dplyr)

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

    titlePanel("Reactivity Test"),

    # Sidebar with two input widgets
    sidebarLayout(
        sidebarPanel(
            selectInput(inputId = "dataset",
                        label = "Input #1 - Dataset",
                        choices = c("mtcars", "iris")),
            selectInput(inputId = "variable",
                        label = "Input #2 - Variable",
                        choices = NULL)
        ),

        # Show a plot of the generated distribution
        mainPanel(
           plotOutput("distPlot")
        )
    )
)

# Define server logic required to draw a histogram
server <- function(input, output) {
    
    input_dataset <- reactive({
        if (input$dataset == "mtcars") {
            return(mtcars)
        } else {
            return(iris)
        }
    })
    
    mtcars_vars <- c("mpg", "cyl", "disp")
    iris_vars <- c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width")

    available_vars <- reactive({
        if (input$dataset == "mtcars") {
            return(mtcars_vars)
        } else {
            return(iris_vars)
        }
    })
    
    observe({
        updateSelectInput(inputId = "variable", label = "Variable", choices = available_vars())
    })
    
    output$distPlot <- renderPlot({
        req(input$dataset, input$variable)
        print(input$dataset)
        print(input$variable)
        
        selected_dataset <- input_dataset()
        selected_variable <- input$variable
        
        filtered_data <- selected_dataset %>% select(selected_variable)

        ggplot(filtered_data, aes(x = get(selected_variable))) + 
            geom_histogram()
    })
}

# Run the application 
shinyApp(ui = ui, server = server)

Upvotes: 8

Views: 1934

Answers (1)

Johan Rosa
Johan Rosa

Reputation: 3152

You can try using the freezeReactiveValue() function, as Hadley Wickham recommends in mastering shiny.

library(shiny)
library(ggplot2)
library(dplyr)

# Define UI for application that draws a histogram
ui <- fluidPage(
  titlePanel("Reactivity Test"),
  
  # Sidebar with two input widgets
  sidebarLayout(
    sidebarPanel(
      
      selectInput(inputId = "dataset",
                  label = "Input #1 - Dataset",
                  choices = c("mtcars", "iris")),
      
      selectInput(inputId = "variable",
                  label = "Input #2 - Variable",
                  choices = NULL)
    ),
    
    # Show a plot of the generated distribution
    mainPanel(
      plotOutput("distPlot")
    )
  )
)

# Define server logic required to draw a histogram
server <- function(input, output, session) {
  
  input_dataset <- reactive({
    if(input$dataset == "mtcars") {
      return(mtcars)
    } else {
      return(iris)
    }
  })
  
  observeEvent(input$dataset, {
    freezeReactiveValue(input, "variable")
    updateSelectInput(session = session, inputId = "variable", choices = names(input_dataset()))
  })
  
  output$distPlot <- renderPlot({
    ggplot(input_dataset(), aes(x = .data[[input$variable]])) +
      geom_histogram()
  })
  
}

# Run the application 
shinyApp(ui = ui, server = server)

Upvotes: 7

Related Questions