updateSelectInput 不触发事件

Hec*_*tor 5 javascript r shiny

在我闪亮的应用程序中,我有两个 SelectInput 对象,其选项在两者之间依赖(两个列表中可以有多个选择)。

当我与小部件 A 交互时,小部件 B 中的选择可能不再适用,因此我想相应地更新小部件 B 中的选择和选择。

有没有一种方法可以使用 updateSelectInput 更新选项和选择而不触发事件?换句话说,有没有办法避免失效input$widgetB

编辑:

下面的例子显示了我的问题。

我曾经browser()追踪反应链。如果小部件 B 仅选择了“X”,则小部件 A 应该仅将“A”和“B”显示为选项(即“C”不再是选项)。类似地,如果小部件 A 仅选择了“C”,则小部件 B 应该仅将“Y”和“Z”显示为选项(即“X”不再是选项)。由于其设置方式,反应链最终将所有选择恢复为初始设置。我不认为如果有一种方法可以updateSelectInput在选择/选择更改时停止使相关小部件无效(请注意,updateSelectInput如果我们用相同的值替换当前选择/选择,那么它足够聪明,不会使相关小部件无效) )。

我有什么想法可以实现预期的结果吗?

library(shiny)

ui <- fluidPage(
  selectInput(
    "WidgetA",
    label = h3("Widget A"),
    choices = c("A", "B", "C"),
    selected = c("A", "B", "C"),
    multiple = TRUE
  ), 
  selectInput(
    "WidgetB",
    label = h3("Widget B"),
    choices = c("X", "Y", "Z"),
    selected = c("X", "Y", "Z"),
    multiple = TRUE
  ),
  tableOutput("table")
)

server <- function(input, output, session) {

  D <- data.frame(A = c("A","A","B","B","B","C","B","C","C","A"),
                  B = c("X","Y","Z","X","Y","Z","X","Y","Z","X"),
                  x = 1:10
                  )

  observeEvent(input$WidgetA,{
    # browser()

    B_choices <- unique(D$B[D$A %in% input$WidgetA])

    # Does not trigger update (i.e., it does not invalidate input$WidgetB) if choices AND selections remain the same
    updateSelectInput(session, "WidgetB", choices = B_choices, selected = B_choices)

    D_ <- D[D$A %in% input$WidgetA & D$B %in% input$WidgetB,]

    output$table <- renderTable(D_)
  })

  observeEvent(input$WidgetB,{
    # browser()

    A_choices <- unique(D$A[D$B %in% input$WidgetB])

    # Does not trigger update (i.e., it does not invalidate input$WidgetA) if choices AND selections remain the same
    updateSelectInput(session, "WidgetA", choices = A_choices, selected = A_choices)

    D_ <- D[D$A %in% input$WidgetA & D$B %in% input$WidgetB,]

    output$table <- renderTable(D_)
  })

}

shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)

GJP*_*ten 0

您可以在服务器端使用 renderUI 来渲染 selectInput,该 selectInput 依赖于另一个输入的值。然后,您可以使用 uiOutput 函数将其添加到您的 UI:

library(shiny)

ui <- fluidPage(

  selectInput(
    "widgetA",
    label = h3("Widget A"),
    choices = c(1,2,3,4)
  ),
  uiOutput("select2")
  )

server <- function(input, output) {
   output$select2 <- renderUI({
     if(input$widgetA %in% c(1,2)) {
    selectInput(
      "WidgetB",
      label = h3("Widget B"),
      choices = c("A", "B", "C")
    ) }
    else {
      selectInput(
        "WidgetB",
        label = h3("Widget B"),
        choices = c("X", "Y", "Z")
      )
    } 
  })
}
shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)