我需要在服务器端为selectInput生成选择(它们将根据数据库中的更改而更改)。如本例所示,除了在服务器端呈现整个UI元素之外,还有其他选择吗?
server <- function(input, output, session) {
data("mtcars")
output$select_cars = renderUI({
selectInput("cyl",
label = "Select cylinder",
choices = mtcars %>% distinct(cyl) %>% pull %>% append("All", after = 0))
})
}
ui = fluidPage(
uiOutput("select_cars")
)
shinyApp(ui, server)
类似于在服务器端创建反应值并将其发送到UI进行渲染?如果是这样,什么是更明智的做法(或者是什么利弊)?
答案 0 :(得分:1)
使用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)
另外,这不是OP的问题,但是我们可以看到他们正在尝试实现“全选”选项,我建议开箱即用的shinyWidgets::pickerInput()
具有此功能(很好的实现):< / p>
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)
更紧密地模仿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)
如果不需要反应来更新输入,甚至可以进一步简化:
server <- function(input, output, session) {
updatePickerInput(session, "cyl", "Select cylinder",
choices = sort(unique(mtcars$cyl)))
}