Column visibility in DT in a shiny app

Hello everyone,
I'm trying to use DT in my shiny app in order to show by default only some columns of my whole dataset, and the let the user select more if he wants.
It should be straightforward with the "Buttons" extension, but I have one problem : I don't know in advance the number of columns of the dataset. I know the indices of the columns I want to display, but there may be between 6 and 30 additional columns that I don't want to display by default.

In the DT documentation, I can't find a way to do this. I have tried the following, which does not work :

library(shiny)
library(DT)

ui <- fluidPage(
    titlePanel("TestDT"),
  DTOutput("iris_table")
)

server <- function(input, output, session) {
  output$iris_table <- renderDT({
    iris
  },
  rownames = FALSE,
  extensions = "Buttons",
  options = list(scrollX = TRUE,
                 dom = "Bfrtip",
                 columnDefs = list(
                   list(targets = c(0, 1), className = "noVis"),
                   list(targets = which(!(1:ncol(iris) %in% c(0, 1))), visible = FALSE)
                 ),
                 buttons = list(
                   list(extend = 'colvis', columns = I(':not(.noVis)'))
                   ))
  )
}
shinyApp(ui = ui, server = server)

The buttons part is to exclude the base columns from the colvis selection, while the columnDefs part is there two separate my columns in two : those that are displayed by default, those that aren't. The which(!(1:ncol(iris) %in% c(0, 1))) does not work.

Thanks in advance.

I've since find a way to do what I want , using dataTableProxyand hideCols, even though this does not look like it should work (shouldn't it throw an error as the output does not exist on the first run of renderDT?), it kind of does?

It is based on this answer on Stackoverflow.

library(shiny)
library(DT)
library(magrittr)

vec_len <- 2:(ncol(iris)-1)

ui <- fluidPage(
  titlePanel("TestDT"),
  DTOutput("iris_table")
)

server <- function(input, output, session) {
  output$iris_table <- renderDT({
    dataTableProxy("iris_table") %>%
      hideCols(vec_len)
    iris
  },
  rownames = FALSE,
  extensions = "Buttons",
  options = list(scrollX = TRUE,
                 dom = "Bfrtip",
                 columnDefs = list(
                   list(targets = c(0, 1), className = "noVis")),
                 buttons = list(
                   list(extend = 'colvis', columns = I(':not(.noVis)'))
                 ))
  )
}
shinyApp(ui = ui, server = server)

If anyone finds a better solution, do not hesitate to post it!

from your first version, change the above for

setdiff( 0:(ncol(iris)-1), 
         c(0,1))
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.