在带有自定义容器的闪亮应用程序中的 DT 数据表中添加垂直线

Add vertical line in a DT datatable in a shiny app with custom container

我想在列组之间添加一条垂直线。这是一个理想的结果:

---------
g1  | g2
---------
a b | a b
---------
1 2 | 3 4
---------

还有一个闪亮的应用程序:

library(shiny)
library(DT)
library(htmltools)

runApp(shinyApp(
  ui <- basicPage(
    DT::dataTableOutput('table1')
  ),
  server = function(input, output) {
    output$table1 <- DT::renderDataTable({
      datatable(data.frame(a1 = 1, b1 = 2, a2 = 3, b2 = 4), rownames = FALSE,
                container = withTags(table(
                  class = 'display',
                  thead(
                    tr(
                      th(colspan = 2, 'g1'),
                      th(colspan = 2, 'g2')
                    ),
                    tr(
                      lapply(rep(c('a', 'b'), 2), th)
                    )
                  )
                ))
      )
    })
  }
))

上面 shiny 应用程序的当前输出:

您可以添加 css class,在单元格右侧添加边框,并使用 columnDefs 选项将其应用于相关列。对于 header,您可以使用 initComplete 回调设置 class。

这是一个例子:

library(shiny)
library(DT)
library(htmltools)

runApp(shinyApp(
  ui <- basicPage(
    tags$head(
      tags$style(HTML(".cell-border-right{border-right: 1px solid #000}"))),
    DT::dataTableOutput('table1')
  ),
  server = function(input, output) {
    output$table1 <- DT::renderDataTable({
      datatable(data.frame(a1 = 1, b1 = 2, a2 = 3, b2 = 4), rownames = FALSE,
                container = withTags(table(
                  class = 'display',
                  thead(
                    tr(
                      th(colspan = 2, 'g1'),
                      th(colspan = 2, 'g2')
                    ),
                    tr(
                      lapply(rep(c('a', 'b'), 2), th)
                    )
                  )
                )),options = list(initComplete = JS(
                  "function(settings, json) {",
                  "var headerBorder = [0,1];",
                  "var header = $(this.api().table().header()).find('tr:first > th').filter(function(index) {return $.inArray(index,headerBorder) > -1 ;}).addClass('cell-border-right');",
                  "}"),columnDefs=list(list(className="dt-right cell-border-right",targets=1))
      ))
    })
  }
))

jquery selector用于select第一行header和第一个th标签,这样边框就是仅添加到 g1 单元格。