Shiny R切换selectInput时如何保留联动pickerInput的已选有效选项
实现方案
要实现跨周期保留有效选中项的效果,只需要在调用updatePickerInput时主动指定selected参数,保留原有已选值里符合当前周期可选范围的部分即可。
修改后的完整可运行代码如下:
library(shiny) library(shinyWidgets) choice_name <- c('UK','USA','UK','USA','BE','BE') choice_id <- c(1, 2, 1, 2, 3, 3) period <- c('period1', 'period1', 'period2', 'period3', 'period3', 'period3') data <- data.frame(choice_name, choice_id, period) choices_picker <- unique(data$choice_id) names(choices_picker) <- unique(data$choice_name) ui <- bootstrapPage( absolutePanel(left = 10, bottom = 10, draggable = TRUE, selectInput(inputId = "input_period", label = "Period", choices = c("Period 1: X to Z" = "period1", "Period 2: X to Y" = "period2", "Period 3: X to X" = "period3"), selected = "period1"), pickerInput(inputId = "picker_cty", label = "Select Country", choices = choices_picker, multiple = TRUE), )) server <- function(input, output, session) { # Reactive pickerInput --------------------------------- observeEvent(input$input_period, { data1 <- data[data$period == input$input_period,] datau <- unique(data$choice_id) data1u <- unique(data1$choice_id) disabled_choices <- ifelse(datau %in% data1u, 0,1) # 筛选当前有效已选值 current_picked <- input$picker_cty keep_selected <- current_picked[current_picked %in% data1u] # 更新pickerInput,保留有效选中项 updatePickerInput(session = session, inputId = "picker_cty", choices = choices_picker, selected = keep_selected, choicesOpt = list( disabled = disabled_choices, style = ifelse(disabled_choices, yes = "color: rgba(119, 119, 119, 0.5);", no = "") )) }, ignoreNULL=FALSE) } shinyApp(ui, server)
效果说明
- 选择period1时选中UK+USA,切换到period2后,UK属于period2的可选范围会保持选中,USA不在可选范围内会被自动排除
- 切换到period3时,原有选中的UK、USA都不在可选范围内会自动清空,仅保留属于当前周期的BE的选中状态(如果之前选过BE的话)
内容的提问来源于stack exchange,提问作者AnEostig
相关产品推荐
相关产品推荐

