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

标签 r shiny dt

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

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

和一个 Shiny 的应用程序开始:
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 的应用程序的当前输出:

enter image description here

最佳答案

您可以添加一个 css 类,在单元格右侧添加边框,并使用 columnDefs 将其应用于相关列。选项。对于标题,您可以使用 initComplete 设置类打回来。

下面是一个例子:

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选择器用于选择标题的第一行和第一个 th标签,这样边框只添加到 g1细胞。

关于r - 在带有自定义容器的 Shiny 应用程序中的 DT 数据表中添加垂直线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36692719/

相关文章:

r - 分配给 LHS 上的空索引(空方括号 x[]<-)

r - 如何在 R 中为栅格创建正确的空间滞后变量?

带有 html 标签的 R Shiny 数据表内容

r - 如何很好地重新缩放格子图形?

r - 基于无序的列对聚合数据框

r - 单元测试 Shiny 的应用程序

R Shiny 数据不可用 "Error: object not found"

react 图侧边栏和选项卡

r - 日期格式随 DT 和 Shiny 而变化

javascript - ColReorder DT 扩展结合 shinyjqui