【问题标题】:Dynamically update two selectInput boxes based on the others selection in R Shiny根据 R Shiny 中的其他选择动态更新两个 selectInput 框
【发布时间】:2021-02-24 00:04:18
【问题描述】:

我正在开发一个闪亮的应用程序并有两个选择输入框。它们都采用相同的输入,我想根据对方的选择更新输入框。

基本上我想删除一个输入框上的选定变量,而另一个输入框的下拉列表中不可用。

vars <- c("A", "B", "C", "D", "E", "F", "G", "H")

selectInput("v1", label = "Select Variable 1", choices = vars),
selectInput("v2", label = "Select Variable 2", choices = vars)

在上面的示例中,如果用户选择选项 A 作为“V1”,我想从 v2 可用的选项中删除 A,反之亦然。我尝试了以下操作但没有成功

  observe({
    updateSelectInput(session, "v1", choices = vars)
  })

observe({
        updateSelectInput(session, "v2", choices = vars)
  })

【问题讨论】:

  • 避免使用函数名作为变量名(vars)

标签: r shiny selectinput


【解决方案1】:

您可以通过使用每个输入来过滤其他输入中的选择来实现此目的:

library(shiny)
my_vars <- c("A", "B", "C", "D", "E", "F", "G", "H")


ui <- fluidPage(
  selectInput("v1", label = "Select Variable 1", choices = my_vars, multiple = TRUE),
  selectInput("v2", label = "Select Variable 2", choices = my_vars, multiple = TRUE)
  
)

server <- function(input, output, session){
  observe({
    if(!is.null(input$v2))
      updateSelectInput(session, "v1", 
                        choices = my_vars[!(my_vars %in% input$v2)], 
                        selected = isolate(input$v1) )
  })
  
  observe({
    if(!is.null(input$v1))
      updateSelectInput(session, "v2", 
                        choices = my_vars[!(my_vars %in% input$v1)], 
                        selected = isolate(input$v2) )
  })
}

shinyApp(ui = ui, server = server)

注意使用isolate 以避免关闭选项之间的列表

如果您不想多选,请使用不同的选择初始化每个输入:

ui <- fluidPage(
  selectInput("v1", label = "Select Variable 1", choices = my_vars, selected = "A"),
  selectInput("v2", label = "Select Variable 2", choices = my_vars, selected = "B")
)

【讨论】:

    猜你喜欢
    • 2023-02-11
    • 2016-12-21
    • 2021-11-26
    • 2019-01-19
    • 2019-12-10
    • 1970-01-01
    • 2019-04-06
    • 1970-01-01
    • 2021-10-22
    相关资源
    最近更新 更多