Frank
Frank

Reputation: 1196

Hide a column in shiny datatable but keep it searchable

The DT package in Shiny produces a table with a searchbar that searches over every column in the table. I have a column of metadata which I do not want to display in the table, but I still want the rows to come up if I search with the search bar.

For example, the app below contains a column titled searchCol . This column is just letters. I want to hide this column in the actual table, and I want to be able to search for the letter b , using the DT search bar, and have the second row show up.

Is there a way to hide the column but have it still work with the search bar?

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)

Upvotes: 0

Views: 618

Answers (1)

starja
starja

Reputation: 10365

I've adapted the answer from here to the format you need to use in DT::datatable. You can use columnDefs to define the render options for the different columns, targets defines which column you mean. Please note that the JS library datatables starts counting columns at 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)

Upvotes: 1

Related Questions