根据 R Shiny 中的其他选择动态更新两个 selectInput 框
Dynamically update two selectInput boxes based on the others selection in R Shiny
我正在开发一个闪亮的应用程序并且有两个选择输入框。他们都接受相同的输入,我想根据对方的选择更新输入框。
基本上我想删除一个输入框上的选定变量,而另一个输入框的下拉列表不可用。
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)
})
您可以通过使用每个输入来过滤其他输入中的选择来实现此目的:
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")
)
我正在开发一个闪亮的应用程序并且有两个选择输入框。他们都接受相同的输入,我想根据对方的选择更新输入框。
基本上我想删除一个输入框上的选定变量,而另一个输入框的下拉列表不可用。
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)
})
您可以通过使用每个输入来过滤其他输入中的选择来实现此目的:
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")
)