Example of using updateSelectInput
:
library(shiny)
ui <- fluidPage(
selectInput("column", "Select column", choices = names(mtcars)),
selectInput("value", "", choices = NULL, multiple = TRUE),
verbatimTextOutput("selected")
)
server <- function(input, output, session) {
observeEvent(input$column, {
updateSelectInput(session, "value", paste("Select", input$column, "value(s)"),
choices = sort(unique(mtcars[[input$column]])))
})
output$selected <- renderText({
paste0(input$column, ": ", paste(input$value, collapse = ", "))
})
}
shinyApp(ui, server)
Also, not OP's question, but we can see they're trying to achieve a "select all" option, I would suggest shinyWidgets::pickerInput()
that has (a nice implementation of) this feature out of the box:
library(shiny)
library(shinyWidgets)
ui <- fluidPage(
selectInput("column", "Select column", choices = names(mtcars)),
pickerInput("value", "", choices = NULL, multiple = TRUE,
options = list(`actions-box` = TRUE)),
verbatimTextOutput("selected")
)
server <- function(input, output, session) {
observeEvent(input$column, {
updatePickerInput(session, "value", paste("Select", input$column, "value(s)"),
choices = sort(unique(mtcars[[input$column]])))
})
output$selected <- renderText({
paste0(input$column, ": ", paste(input$value, collapse = ", "))
})
}
shinyApp(ui, server)
Example that more closely mimicks OP:
ui <- fluidPage(
pickerInput("cyl", "", choices = NULL, multiple = TRUE,
options = list(`actions-box` = TRUE))
)
server <- function(input, output, session) {
observe({
updatePickerInput(session, "cyl", "Select cylinder",
choices = sort(unique(mtcars$cyl)))
})
}
shinyApp(ui, server)
which can even be simplified further if reactivity is not needed to update the input:
server <- function(input, output, session) {
updatePickerInput(session, "cyl", "Select cylinder",
choices = sort(unique(mtcars$cyl)))
}
update*Input()
is preferable. It gives code that is clearer and easier to reason about – Aurèleexample("updateSelectInput", package = "shiny")
could do, and readinghelp(updateSelectInput)
, also see my answer for another example (and for achieving "select all" in a nicer way) – Aurèle