4
votes

Is there a way (other than a 'colvis' button) to dynamically update which columns are visible in a DT::datatabe while using the DT::replaceData to update the table?

(The reason I can not use the 'colvis' button (as shown here:https://rstudio.github.io/DT/extensions.html) is I need to have a few different short cut convenient buttons that hide and show multiple complex patterns at once.)

This is an example of how I would initiate my app. Is there a way in js or the server-side to hide and show columns? Thanks!

library(shiny)
library(DT)
shinyApp(
  ui = fluidPage(
    fluidRow(
      column(2, actionButton('refresh', 'Refresh Data', icon = icon('refresh'))),
      column(10, DT::dataTableOutput('foo'))
    )
  ),

  server = function(input, output, session) {

    df = iris
    n = nrow(df)
    df$ID = seq_len(n)

    loopData = reactive({
      input$refresh
      df$ID <<- c(df$ID[n], df$ID[-n])
      df
    })

    output$foo = DT::renderDataTable(isolate(DT::datatable(loopData(),
                                                           options = list(
                                                             columnDefs = list(list(visible=FALSE,targets=c(0,1,2))))

    )))

proxy = dataTableProxy('foo')

observe({
  replaceData(proxy, loopData(), resetPaging = FALSE)
})
  }
)