R Shiny selectInput dependent on another input

Symbol of coding on a computer screen

How to create a dynamic R Shiny selectInput control with choices filtered by another select input



Filter selectInput choices based on a previous user input

It’s often the case that we want the choices provided in a selectInput to be dependent on a previous select input – the user makes one selection and this filters the choices for the next selectInput control.

There are various ways to filter one selectInput based on another select input, and in this post we’re going to look at two different methods:


About R Shiny selectInput controls

R Shiny selectInput controls create interactive user selections which are used in dynamic outputs such as charts, maps and tables.

The result (output) for a selectInput selection control can only be captured in a ‘reactive’ control [such as renderText(), renderTable(), renderPlot(), renderUI() ].

>> See our post here about how to create a Shiny selectInput control, and how to use the outputs from selectInput.

Method 1: create the dependent selectInput with renderUI()

In this method, we create the second selectInput control in an output variable, with renderUI().

Steps to create a dynamic selectInput control using renderUI()
  1. selectInput(): create the first selectInput control which will filter the choices for the second selectInput.
  2. output$variable <- renderUI(): To filter the choices for the second selectInput control, create it in an output variable using renderUI().
  3. uiOutput(): add the second selectInput control to the user interface via a uiOutput() control. This can be written higher up in the flow of the R script; R will look through the entire script for the output ID that is being called.

Below is the R code for the output variable which creates the second selectInput, name (ID) 'cat_choice'. It contains the reactive function renderUI() which creates the second selectInput. The output 'cat_choice' can be placed in the user interface using uiOutput("outputID").

output$cat_choice <- renderUI({
  selectInput(inputId="choose_item",
            label="Select item", 
            choices = unique(choices_table 
            [choices_table$category==input$choose_category, 
            "items"]))
                             })

uiOutput("cat_choice")

>> Go to the full R code example for Method 1 shown on the next page

Pages: 1 2 3 4