writer_typer
writer_typer

Reputation: 798

How to update selectInput?

I'm trying to update the choices in a selecInput using values from a previous selectInput, but I'm unable to get the observer to work.

I tried using observe, observeEvent and without it, but the options are not updated.

library(shiny)

ui <-  fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectInput("select_data", label = "Select Data", choices = c(" ", "islands", "iris", "mtcars")),
      selectInput("select_var", label = "Select Variable", choices = "" )
      ),
    mainPanel(
      tableOutput("table")
      )
    )
  )

 
server <- function(input, output, session) {
  
 observeEvent(input$select_data,{
    updateSelectInput(session, "select_var", choices = names(input$select_data))
    
  })
  
  varnames <- reactive({
    input$select_data
  })
  
  output$table <- renderTable({
    head(varnames[[input$select_var]])
  })
}

shinyApp(ui, server)

Upvotes: 0

Views: 443

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388797

You can store the data in a named list from which you can select based on dropdown.

library(shiny)


list_data <- tibble::lst(islands, iris, mtcars)

ui <-  fluidPage(
  sidebarLayout(
    sidebarPanel(
      selectInput("select_data", label = "Select Data", choices = c(" ", names(list_data))),
      selectInput("select_var", label = "Select Variable", choices = "")
    ),
    mainPanel(
      tableOutput("table")
    )
  )
)


server <- function(input, output, session) {
  
  observeEvent(input$select_data,{
    updateSelectInput(session, "select_var", choices = names(list_data[[input$select_data]]))
    
  })
  
  
  output$table <- renderTable({
    if(input$select_data != '' && input$select_var != '')
      head(list_data[[input$select_data]][input$select_var])
  })
}

shinyApp(ui, server)

Upvotes: 1

Related Questions