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

如何为datamods包的select_group_ui设置默认选中选项?

如何给datamods的select_group组件设置默认选中项

你之前在vs_args里传selected = "Audi"不生效,是因为select_group模块的默认选中逻辑由server端的select_group_server()函数控制,而非UI层的vs_args——vs_args仅用于传递底层selectizeInput组件的通用参数,没法单独指定某个筛选器的默认值。

正确做法是在select_group_server()中使用selected参数,这个参数需要传入一个命名列表,列表的键对应你要设置的变量名(比如Manufacturer),值就是该变量要默认选中的选项。

以下是修改后的完整代码:

library(shiny)
library(datamods)
library(shinyWidgets)
library(reactable)

ui <- fluidPage(
  fluidRow(
    column(
      width = 10, offset = 1,
      tags$h3("Filter data with select group module"),
      shinyWidgets::panel(
        select_group_ui(
          id = "my-filters",
          params = list(
            list(inputId = "Manufacturer", label = "Manufacturer:"),
            list(inputId = "Type", label = "Type:"),
            list(inputId = "AirBags", label = "AirBags:"),
            list(inputId = "DriveTrain", label = "DriveTrain:")
          ), 
          vs_args = list(disableSelectAll = FALSE)
        ),
        status = "primary"
      ),
      reactableOutput(outputId = "table"),
      tags$b("Inputs values:"),
      verbatimTextOutput("inputs")
    )
  )
)

server <- function(input, output, session) {
  res_mod <- select_group_server(
    id = "my-filters",
    data = reactive(MASS::Cars93),
    vars = reactive(c("Manufacturer", "Type", "AirBags", "DriveTrain")),
    # 设置默认选中项:给Manufacturer指定默认值"Audi"
    selected = reactive(list(Manufacturer = "Audi"))
  )
  
  output$table <- renderReactable({
    reactable(res_mod())
  })
  
  output$inputs <- renderPrint({
    attr(res_mod(), "inputs")
  })

}

if (interactive())
  shinyApp(ui, server)

关键说明:

  • selected参数接受响应式命名列表,你可以为多个变量设置默认值,比如list(Manufacturer = "Audi", Type = "Sedan")
  • 如果某个变量不需要默认选中项,直接不加入列表即可,或者设为NULL
  • 启动应用后,Manufacturer筛选器会自动选中"Audi",表格同步过滤对应数据,inputs输出也能看到这个默认值

内容的提问来源于stack exchange,提问作者Jo Lo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 17:05:08