How to create a dynamic R Shiny selectInput control with choices filtered by another select input
Links to topics on this page
- Filter selectInput choices based on another select input
- About Shiny selectInput selection controls
- Method 1: create the dependent selectInput with renderUI()
- Method 1 steps
- Method 1 code example
- Method 2: create the dependent selectInput using observe() with updateSelectInput()
- Method 2 steps
- Method 2 code example – observe() with updateSelectInput()
- Method 2 code example – observeEvent() with updateSelectInput()
- Related links and topics
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:
- Method 1: create the
selectInput
in an output variable withrenderUI()
- Method 2: use
observe()
orobserveEvent()
functions withupdateSelectInput()
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()
selectInput()
: create the first selectInput control which will filter the choices for the second selectInput.output$variable <- renderUI()
: To filter the choices for the second selectInput control, create it in an output variable using renderUI().uiOutput()
: add the second selectInput control to the user interface via auiOutput()
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