Search code examples
rshinyshinyappsshiny-reactivityselectinput

Could I get the choices of a SelectInput in the ui from a reactive function in server? (RShiny)


I have created a reactive function in the server to get a list of elements. The idea is to show each element of the list as a individual choice in the ui, just like selectInput does in the ui.

I wrote an example with mtcars.

library(shiny)

ui <- fluidPage(
  
  titlePanel("Old Faithful Geyser Data"),
  
  sidebarLayout(
    sidebarPanel(
      selectInput(inputId = options, "Select one", choices = cars())
      
    ),
    
    mainPanel(
      verbatimTextOutput("print")
    )
  )
)

server <- function(input, output) {
  
  cars <- reactive({
    data("mtcars")
    cars <- list(rownames(mtcars))
    return(cars)
  })
  
  output$print <- renderPrint(cars())
  
}

# Run the application 
shinyApp(ui = ui, server = server)

If you delete or comment this line: selectInput(inputId = options, "Select one", choices = cars()) in the ui, the app works. The output is like this:

[[1]]
 [1] "Mazda RX4"           "Mazda RX4 Wag"       "Datsun 710"         
 [4] "Hornet 4 Drive"      "Hornet Sportabout"   "Valiant"            
 [7] "Duster 360"          "Merc 240D"           "Merc 230"           
[10] "Merc 280"            "Merc 280C"           "Merc 450SE"         
[13] "Merc 450SL"          "Merc 450SLC"         "Cadillac Fleetwood" 
[16] "Lincoln Continental" "Chrysler Imperial"   "Fiat 128"           
[19] "Honda Civic"         "Toyota Corolla"      "Toyota Corona"      
[22] "Dodge Challenger"    "AMC Javelin"         "Camaro Z28"         
[25] "Pontiac Firebird"    "Fiat X1-9"           "Porsche 914-2"      
[28] "Lotus Europa"        "Ford Pantera L"      "Ferrari Dino"       
[31] "Maserati Bora"       "Volvo 142E" 

However, if I try to put a selectInput in the ui to show that list, I get this error: Error in cars (): could not find function "cars"

I don't know if it is possible, but could I show each element of that list in a selection bar in the ui? In order to the user be able to select an option and do other things that I have to program.

Thanks very much in advance,

Regards


Solution

  • Generate the selectInput on the server side.

    library(shiny)
    
    ui <- fluidPage(
      titlePanel("Old Faithful Geyser Data"),
      sidebarLayout(
        sidebarPanel(
          uiOutput('selectUI')
        ),
        mainPanel(
          verbatimTextOutput("print")
        )
      )
    )
    
    server <- function(input, output) {
      
      cars <- reactive({
        data("mtcars")
        cars <- rownames(mtcars)
        return(cars)
      })
      
      output$selectUI <- renderUI({
        selectInput(inputId = 'options', "Select one", choices = cars())  
      })
      
      output$print <- renderPrint(cars())
      
    }
    
    # Run the application 
    shinyApp(ui = ui, server = server)
    

    enter image description here