You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R Shiny如何强制用户从两个pickerInput累计选择至少5个选项

解决方案

核心调整说明

  • 新增响应式逻辑统计list_1、list_2两个pickerInput的累计选中数量,同时合并所有选中的机构名称
  • 增加条件判断分支:累计选中数量≥5时输出所有选中内容,不足则输出指定提示文本
  • 修复原代码中输入ID引用错误的问题:原代码错误引用input$list1/input$list2,实际组件注册的ID为list_1/list_2

完整可运行代码

# LIBRARIES ----
library(shiny)
library(shinyWidgets)

# USER INTERFACE ----
ui <- fluidPage(
  sidebarLayout(
    sidebarPanel = sidebarPanel(
      width = 4,
      p("Peer Group Comparisons"),
      pickerInput(
        inputId  = "list_1",
        label    = "Organizations from List 1",
        choices  = c("a", "b", "c", "d"),
        options  = pickerOptions(
          actionsBox = TRUE,
          liveSearch = TRUE),
        multiple = TRUE 
      ),
      pickerInput(
        inputId  = "list_2",
        label    = "Organizations from List 2",
        choices  = c("e", "f", "g", "h", "x", "y", "z"),
        options  = pickerOptions(
          actionsBox = TRUE,
          liveSearch = TRUE),
        multiple = TRUE 
      )
    ),
    mainPanel = mainPanel(
      width = 8,
      textOutput("results")
    )
  )
)

# SERVER ----
server <- function(input, output, session) {
  # 响应式获取选中项和总数量
  selected_data <- reactive({
    s1 <- input$list_1
    s2 <- input$list_2
    all_selected <- c(s1, s2)
    return(
      list(
        count = length(all_selected),
        orgs = all_selected
      )
    )
  })

  output$results <- renderText({
    sel <- selected_data()
    if (sel$count >= 5) {
      paste0("已选中的机构:", paste(sel$orgs, collapse = "、"))
    } else {
      "请至少选择5个机构才可继续操作!"
    }
  })
}

shinyApp(ui, server)

内容的提问来源于stack exchange,提问作者Ahmad Mobin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 21:57:03