DT updateSearch()函数keywords参数的正确语法咨询
在Shiny中使用
updateSearch()指定列筛选的参数格式说明 核心格式规则
updateSearch()的columns参数需传入列表,每个元素对应目标列的筛选规则(列索引从0开始),规则格式完全取决于列的数据类型:
1. 字符/因子列筛选
- 必须使用JSON数组字符串指定匹配值,比如
'["setosa", "versicolor"]' - 示例代码:
library(shiny) library(DT) ui <- fluidPage( actionButton("filter_char", "筛选鸢尾花品种为setosa"), DTOutput("iris_table") ) server <- function(input, output, session) { output$iris_table <- renderDT({ datatable(iris, filter = "top") }) observeEvent(input$filter_char, { updateSearch(session, "iris_table", columns = list( # 第0列(Species)筛选setosa list(search = list(value = '["setosa"]', regex = FALSE)) ) ) }) } shinyApp(ui, server)
2. 数字列筛选
数字列支持两种筛选逻辑,对应不同格式:
- 范围筛选:用
'[最小值, 最大值]'格式的字符串,比如'[5, 7]'(筛选5到7之间的数值) - 精确匹配:直接传入数值的字符串形式,比如
'6.4' - 示例代码:
observeEvent(input$filter_num, { updateSearch(session, "iris_table", columns = list( # 第1列(Sepal.Width)筛选2到3之间的值 list(search = list(value = '[2, 3]', regex = FALSE)) ) ) })
3. 多列同时筛选
在columns列表中按列索引依次添加规则即可:
observeEvent(input$filter_multi, { updateSearch(session, "iris_table", columns = list( # 第0列筛选setosa list(search = list(value = '["setosa"]', regex = FALSE)), # 第2列(Petal.Length)筛选1到2之间的值 list(search = list(value = '[1, 2]', regex = FALSE)) ) ) })
关键注意事项
- 所有筛选值必须以字符串形式传入,哪怕是数字范围也要用引号包裹
regex = FALSE为默认值,若需正则匹配可设为TRUE,但字符列的数组格式仍需保留- 列索引从0开始,对应DT表格的第一列到最后一列
内容的提问来源于stack exchange,提问作者SpikyClip
相关产品推荐
相关产品推荐

