Multiple datasets, how to update selectInput before execution of renderPlot

Hello everyone,

I'm trying to build a data visualization app with Shiny. Several datasets can be loaded and each time a new dataset is loaded a selectInput is updated with the names of the variable in the dataset. Depending on the selected variable a plot is given as output.

Hereafter, a short example:

library(shiny)

ui <- fluidPage(
  titlePanel(
    "BEAMM - Data visualisation tool"
  ),
  sidebarLayout(
    sidebarPanel(
      selectInput("dataset",
                  label = "Select a dataset:",
                  choices = c("dataset1", "dataset2")),
      selectInput("var",
                  label = "Select a variable:",
                  choices = NULL),
    ),
    mainPanel(
      plotOutput("plot")
    )
  )
)

server <- function(input, output, session) {

  inputData <- reactive({
    if (input$dataset == "dataset1") {
      df <- data.frame(x1 = rnorm(100),
                       x2 = rnorm(100))
    } else if (input$dataset == "dataset2") {
      df <- data.frame(y1 = rnorm(100),
                       y2 = rnorm(100))
    }
    df
  })

  observe({
    inputData()
    var_names <- colnames(inputData())
    updateSelectInput(session, "var", choices = var_names, selected = var_names[1])
  })

  output$plot <- renderPlot({
    req(input$var, cancelOutput = TRUE)
    inputData() %>% ggplot(aes(x = !!sym(input$var))) + geom_density()
  })


}

shinyApp(ui, server)

The problem appears when switching from "dataset1" to "dataset2". Before showing the correct plot of variable "y1", there is an error: variable "x1" is not found. My question is: how is possible to update input$var before generating the plot and avoid this error?

Thanks for your help,

Best regards,

Alessandro

try

  output$plot <- renderPlot({
    req(input$var, cancelOutput = TRUE)

    if( ! input$var %in% names(inputData()))
      return(NULL)

    inputData() %>% ggplot(aes(x = !!sym(input$var))) + geom_density()
  })
1 Like

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.

@nirgrahamuk Thanks a lot! That works!

Then, a similar solution can be obtained using the req() function too:

output$plot <- renderPlot({
   req(input$var, cancelOutput = TRUE)
   req(input$var %in% names(inputData()), cancelOutput = TRUE)

   inputData() %>% ggplot(aes(x = !!sym(input$var))) + geom_density()
 })