Responsive Inputs

In each pair of inputs, the first passes values to a renderUI() function in server, which then determines the choices in the second input.



show with app
library(shiny)

ui <-
  fluidPage (
    h3("Responsive Inputs"),
    
    p("In each pair of inputs, the first passes values to a renderUI() function in server, which then determines the choices in the second input."),
    
    hr(),
    
    radioButtons(inputId = "region",
                 label = "Pick a region of the US:",
                 choices = levels(state.region)),
    
    uiOutput(outputId = "ui1"),
    
    hr(),
    
    selectInput(inputId = "first_letters", 
                label = "Pick the first letter of variables:", 
                # first letters of mtcars variables
                choices = sort(unique(substr(names(mtcars), 1, 1))),
                selected = "d",
                multiple = T),
    
    uiOutput(outputId = "ui2")
  
  )

server <-
  function(input, output) {
    output$ui1 <-
      renderUI({
        selectInput(inputId = "state", 
                    label = "Pick a state in that region:",
                    choices = state.name[state.region == input$region])
      })
    
    output$ui2 <- 
      renderUI({
        selectInput(inputId = "vars", 
                    label = "Pick a variable from the mtcars dataset starting with one of these letters:",
                    # get variables starting with any of the selected letters
                    choices = sort(names(mtcars)[grep(paste0("^", input$first_letters, collapse = "|"), names(mtcars))]))})
  }

shinyApp(ui = ui, server = server, options = list(display.mode = "showcase"))