App Structure
I have a Shiny app with the typical sidebar panel + mainpanel structure.
- Sidebar panel: There are multiple selectInput widgets within the sidebarpanel, where the choices within each selectInput are dependent upon the previous selectInput's selected value. (i.e., user selects a dataset from selectInput 1 & a variable from selectInput 2, where the variables available as "choices" in selectInput #2 are dependent on Input 1's selection)
- Main panel: There is a basic ggplot2 visualization, which is dependent upon the 2 input selections (dataset and variable) made in the sidebar panel.
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
- As a UX requirement, I am avoiding using a button to render the plot. I need the plot to update dynamically in real-time based on selections.
- In my reprex, I included print statements to depict how the plot attempts to update with an invalid combo of selections.
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)