如何在DT中使用ColVis插件隐藏自定义容器中的多个列?

时间:2017-10-23 20:15:37

标签: javascript r datatables shiny dt

我有一个闪亮的应用程序,其中我使用DT库来可视化表格。我正在使用容器来渲染表。

sketch = htmltools::withTags(table(
class = 'display',
thead(
  tr(
    th(rowspan = 2, 'Name'),
    th(rowspan = 2, 'Description'),
    th(rowspan = 2, 'From'),
    th(rowspan = 2, 'To'),
    th(rowspan = 2, 'Duration'),
    th(colspan = 3, 'Rain', style="text-align:center"),
    th(colspan = 3, 'Flow', style="text-align:center"),
    th(colspan = 3, 'Depth', style="text-align:center"),
    th(colspan = 3, 'Velocity', style="text-align:center")
  ),
  tr(
    lapply(rep(c('Min', 'Max', 'Mean'), 4), th)
  )
)))
  output$table2 <- DT::renderDataTable({
    datatable(eventSelection[[input$options]], class = 'cell-border stripe table-hover', rownames = FALSE, container = sketch,
              extensions = 'Buttons', options = list(scrollX = TRUE, dom = 'Bfrtip', buttons = I('colvis'))
              ) %>%
      formatDate(c(3,4), method='toLocaleString') %>%
      formatRound(5:17, digits = 3)
  })

表格如下:

Shiny app table with Column Visibility options

我希望在列可见性选项卡中有Rain,Flow,Depth,Velocity选项,并且当我点击它们时能够隐藏相应的Min,Max和Mean统计列。什么是最好的方式?

谢谢!

1 个答案:

答案 0 :(得分:0)

我能够通过使用datatables文档来实现。

以下是代码:

  sketch = htmltools::withTags(table(
class = 'display',
thead(
  tr(
    th(rowspan = 2, 'Name'),
    th(rowspan = 2, 'Description'),
    th(rowspan = 2, 'From'),
    th(rowspan = 2, 'To'),
    th(rowspan = 2, 'Duration'),
    th(colspan = 3, 'Rain', style="text-align:center"),
    th(colspan = 3, 'Flow', style="text-align:center"),
    th(colspan = 3, 'Depth', style="text-align:center"),
    th(colspan = 3, 'Velocity', style="text-align:center")
  ),
  tr(
    lapply(rep(c('Min', 'Max', 'Mean'), 4), th)
  )
)))



 button_list <- list(list(extend='colvisGroup', text="Rain", show=c(5:7)),
                      list(extend='colvisGroup', text="Flow", show=c(8:10)),
                      list(extend='colvisGroup', text="Depth", show=c(11:13)),
                      list(extend='colvisGroup', text="Velocity", show=c(14:16)),
                      list(extend='colvisGroup', text="Hide all", hide=c(5:16))
                      )

  output$table2 <- DT::renderDataTable({
    datatable(eventSelection[[input$options]], class = 'cell-border stripe table-hover', rownames = FALSE, container = sketch,
              extensions = 'Buttons', options = list(scrollX = TRUE, dom = 'Bfrtip',
                                                     columnDefs = list(list(visible=FALSE, targets=c(5:16))),
                                                     buttons = button_list)
              ) %>%
      formatDate(c(3,4), method='toLocaleString') %>%
      formatRound(5:17, digits = 3)
  })