Search code examples
rshinyselectinput

Shiny - Changing the number of choices in selectInput()


I want to change the number of choices in selectInput(). The following reprex works if the new choices are equal in number to the original choices, but if additional (or fewer) choices are offered, the code does not work. How can I get shiny to accept not just new choices for selectInput(), but a new number of choices? Thanks in advance for any help.

Philip


    library(shiny)
    ui <- fluidPage(
      tabPanel("tbls",
        selectInput("tab1",label="Pick a table:",choices=c("a","b","c")),
        selectInput("cht1",label="Pick a time series:",choices=c("d","e","f"))
      )
    )
    server <- function(input,output,session) {
      Nchoices <- reactive({case_when(
        input$tab1=="a" ~c("d","e","f"),
        input$tab1=="b" ~c("g","h","i"),
        input$tab1=="c" ~c("j","k","l","m") # adding one more choice breaks the code
      )}) 
      observe({updateSelectInput(session,"cht1",
        label="Pick a time series:",choices=Nchoices(),selected=NULL)})
      observe(print(Nchoices()))
    
    }
    shinyApp(ui, server)


Solution

  • Instead of case_when, try to use switch. Also, renderUI might be useful. Try this

    library(shiny)
    ui <- fluidPage(
      tabPanel("tbls",
               selectInput("tab1",label="Pick a table:",choices=c("a","b","c")),
               uiOutput("myselect")
               #selectInput("cht1",label="Pick a time series:",choices=c("d","e","f"))
      )
    )
    server <- function(input,output,session) {
      
      Nchoices <- reactive({
        switch(input$tab1, 
               "a" = c("d","e","f"),
               "b" = c("g","h"),
               "c" = c("j","k","l","m") # adding one more choice breaks the code
        )
      })
      
      output$myselect <- renderUI({
        req(input$tab1)
        selectInput("cht1",label="Pick a time series:",choices=Nchoices())
      })
     
      observe(print(Nchoices()))
      
    }
    shinyApp(ui, server)
    

    Please note that in case_when All RHS values need to be of the same type. Inconsistent types will throw an error.