如何在数据表中添加垂直线?

时间:2019-05-15 05:35:48

标签: r dt

我想在3列之间添加一条线:“物种萼片”和“花瓣”。 我该怎么办?

sketch = htmltools::withTags(table(
  class = 'display',
  thead(
    tr(
      th(rowspan = 2, 'Species'),
      th(colspan = 2, 'Sepal'),
      th(colspan = 2, 'Petal')
    ),
    tr(
      lapply(rep(c('Length', 'Width'), 2), th)
    )
  )
))
print(sketch)
datatable(iris[1:20, c(5, 1:4)], container = sketch, rownames = FALSE)

enter image description here

2 个答案:

答案 0 :(得分:2)

你可以

datatable(iris[1:20, c(5, 1:4)], container = sketch, rownames = FALSE) %>% 
  formatStyle(c(1,3), `border-right` = "solid 2px")

enter image description here

对于标题中的边框,可以在sketch中设置CSS:

sketch = htmltools::withTags(table(
  class = 'display',
  thead(
    tr(
      th(rowspan = 2, style = "border-right: solid 2px;", 'Species'),
      th(colspan = 2, style = "border-right: solid 2px;", 'Sepal'),
      th(colspan = 2, 'Petal')
    ),
    tr(
      th("Length"),
      th(style = "border-right: solid 2px;", "Width"),
      th("Length"),
      th("Width")
    )
  )
))

enter image description here

答案 1 :(得分:1)

您可以添加一个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单元格。