首页 > 解决方案 > 隐藏闪亮数据表中的列,但保持可搜索

问题描述

Shiny 中的 DT 包生成一个带有搜索栏的表格,该搜索栏搜索表格中的每一列。我有一列不想在表格中显示的元数据,但是如果我使用搜索栏进行搜索,我仍然希望这些行出现。

例如,下面的应用程序包含一个标题为 的列searchCol 。这个专栏只是字母。我想在实际表中隐藏此列,并且我希望能够b使用 DT 搜索栏搜索 letter ,并显示第二行。

有没有办法隐藏该列但它仍然可以与搜索栏一起使用?

library(shiny)
library(DT)
ui <- fluidPage(
    DTOutput('tbl1'),
)
server <- function(input, output, session) {
    output$tbl1 <- DT::renderDT(server = TRUE, {
        datatable(
            cbind(data.frame(replicate(3,sample(0:1,26,rep=TRUE))), data.frame(searchCol = letters)),
            escape = FALSE,
            rownames = FALSE, 
            filter = list(position = "top", clear = FALSE, plain = TRUE),             
            selection = "single",
            options = list(
                autoWidth = TRUE,
                pageLength = 50,
                lengthMenu = c(50, 100, 1000), 
                dom = 'Blfrtip',             
                buttons = c('copy', 'excel')
            )
        )
    })
}
shinyApp(ui, server)

标签: rshinydatatables

解决方案


我已将此处的答案调整为您需要在DT::datatable. 您可以使用columnDefs来定义不同列的渲染选项,targets定义您所指的列。请注意,JS 库datatables从 0 开始计数列。

library(shiny)
library(DT)
ui <- fluidPage(
  DTOutput('tbl1'),
)
server <- function(input, output, session) {
  output$tbl1 <- DT::renderDT(server = TRUE, {
    datatable(
      cbind(data.frame(replicate(3,sample(0:1,26,rep=TRUE))), data.frame(searchCol = letters)),
      escape = FALSE,
      rownames = FALSE, 
      filter = list(position = "top", clear = FALSE, plain = TRUE),             
      selection = "single",
      options = list(
        autoWidth = TRUE,
        pageLength = 50,
        lengthMenu = c(50, 100, 1000), 
        dom = 'Blfrtip',             
        buttons = c('copy', 'excel'),
        columnDefs = list(
          list(
            targets = 3,
            searchable = TRUE,
            visible = FALSE
          )
        )
      )
    )
  })
}
shinyApp(ui, server)

推荐阅读