首页 > 解决方案 > 在 Shiny 中,我只想在 UI 加载期间更新选择输入()一次

问题描述

我有一个下拉菜单(SelectInput),我只想更新一次,并在上传 UI 期间以编程方式将其加载到项目列表中。我把它放在渲染函数中,但问题是它一次又一次地重置。

标签: rshiny-server

解决方案


selectInput具有允许您设置初始状态的参数。在这些参数中,您可以choices用于提供选项和selected设置默认值。请运行?shiny::selectInput以获取更多详细信息。

如果您想在响应式上下文中的用户交互时对其进行更新,则将其呈现在server侧面或最好使用updateSelectInput会有所帮助。

这是一个最小的例子:

library(shiny)

ui <- fluidPage(
  selectInput(
    inputId = "digits_input", 
    label = "Digits:", 
    choices = 0:9
    ## other arguments with default values:
    # selected = NULL,
    # multiple = FALSE,
    # selectize = TRUE, 
    # width = NULL, 
    # size = NULL
  ),

  selectInput(
    inputId = "letters_input", 
    label = "Lower case letters:", 
    choices = letters,
    selected = c("a", "b", "c"), # initially selected items 
    multiple = T # to be able to select multiple items
  ),

  actionButton(
    inputId = "update",
    label = "Capitalize"
  )

)

server <- function(session, input, output) {
  observeEvent(input$update, {
    updateSelectInput(
      session,
      inputId = "letters_input",
      label = "Upper case letters:",
      choices = LETTERS,
      selected = c("A", "B", "C")
    )
  })
}

shinyApp(ui = ui, server = server)

推荐阅读