Shiny应用开发:响应式pickerInput实现及双参数匹配数据展示问题
核心修改点
- 修复品牌提取正则的转义问题:原代码中
gsub的反向引用\1需改为\\1,否则无法正确提取车辆品牌 - 调整pickerInput联动逻辑:默认直接仅展示当前选中气缸数对应的可用品牌,也可根据需要保留禁用无关选项的交互形式
- 新增双重筛选的响应式数据集:同时匹配选中的气缸数和品牌参数
- 修正表格输出逻辑,绑定筛选后的响应式数据
完整可运行代码
df <- mtcars df$brand <- rownames(mtcars) # 修复正则转义问题 df$brand <- gsub("([A-Za-z]+).*", "\\1", df$brand) if (interactive()) { library(shiny) library(shinyWidgets) library(shinythemes) library(shinycssloaders) # 定义UI ui <- fluidPage( titlePanel("Reproducible Example"), sidebarLayout( sidebarPanel( selectInput(inputId = "input_cyl", label = "Cyl", choices = c("6", "4", "8")), pickerInput( inputId = "picker_cny", label = "Select Company", choices = unique(df$brand), options = list(`actions-box` = TRUE), multiple = TRUE), width = 2), mainPanel( tableOutput("table"), width = 10) )) # 定义服务端 server <- function(input, output, session) { # 联动更新品牌选择器 observeEvent(input$input_cyl, { target_cyl <- as.integer(input$input_cyl) # 筛选当前气缸数对应的所有可用品牌 valid_brands <- unique(df[df$cyl == target_cyl, "brand"]) updatePickerInput(session = session, inputId = "picker_cny", choices = valid_brands) }, ignoreInit = FALSE) # 初始加载也执行,保证首次打开品牌选择器和默认气缸数匹配 # 定义响应式筛选数据集 filtered_data <- reactive({ req(input$input_cyl, input$picker_cny) df[df$cyl == as.integer(input$input_cyl) & df$brand %in% input$picker_cny, ] }) # 输出筛选后的表格 output$table <- renderTable(filtered_data()) } } # 运行应用 shinyApp(ui = ui, server = server)
可选交互方案(保留所有品牌、禁用不符合条件选项)
如果需要展示全部品牌、仅禁用不符合气缸数的选项,可将上述服务端中observeEvent的代码替换为以下内容:
observeEvent(input$input_cyl, { target_cyl <- as.integer(input$input_cyl) # 计算每个品牌是否为当前气缸数可用 all_brands <- unique(df$brand) disabled <- !all_brands %in% unique(df[df$cyl == target_cyl, "brand"]) updatePickerInput(session = session, inputId = "picker_cny", choices = all_brands, choicesOpt = list( disabled = disabled, style = ifelse(disabled, "color: rgba(119, 119, 119, 0.5);", "") )) }, ignoreInit = FALSE)
内容的提问来源于stack exchange,提问作者AnEostig
相关产品推荐
相关产品推荐

