2

I want to display a DT table with customised nested containers in the shiny app. Users concluded that it's difficult to distinguish between different header sections, i.e. quarters and years. Is there a way of making header borders more pronounced, e.g. by adding vertical borders? I'd rather avoid distinguishing between the header sections by colour, like suggested here. Here's an example of the datatable, for one year only (the shiny app supports multiple years):

library(DT)
library(htmltools)
library(dplyr)


## quarterly breakdown
df_qrt <- data.frame(
  group = LETTERS[1:6],
  year = rep(2017, 6),
  Q1_2017A = rnorm(6),
  Q1_2017B = rnorm(6),
  Q2_2017A = rnorm(6),
  Q2_2017B = rnorm(6),
  Q3_2017A = rnorm(6),
  Q3_2017B = rnorm(6),
  Q4_2017A = rnorm(6),
  Q4_2017B = rnorm(6)
)

sketch_qrt = htmltools::withTags(
  table(class = 'display',
        thead(tr(
          th(class = 'dt-center', 
             rowspan = 3,
             'Group'),
          lapply(unique(df_qrt$year),
                 th, colspan = 8)
        ),
        tr(class = 'dt-center', 
          lapply(paste0('Q', 1:4),
                 th, colspan = 2)
        ),

        tr(lapply(rep(
          c('Alpha', 'Beta'), 4
        ), th))
        ))
)


DT::datatable(dplyr::select(df_qrt, -year),
              container = sketch_qrt,
              class = 'cell-border',
              rownames = FALSE,
              fillContainer = TRUE)
Kasia Kulma
  • 1,683
  • 1
  • 14
  • 39

1 Answers1

3
sketch_qrt = htmltools::withTags(
  table(class = 'display',
        thead(tr(
          th(class = 'dt-center', style = "border-top: solid 3px",
             rowspan = 3,
             'Group'),
          lapply(unique(df_qrt$year), style = "border-top: solid 3px",
                 th, colspan = 8)
        ),
        tr(class = 'dt-center', 
           lapply(paste0('Q', 1:4),
                  th, colspan = 2)
        ),

        tr(lapply(rep(
          c('Alpha', 'Beta'), 4
        ), th))
        ))
)

headerCallback <- c(
  "function(thead, data, start, end, display){",
  "  $(thead).closest('thead').find('th').css('border-right', 'solid 3px');",
  "  $(thead).closest('thead').find('th').eq(0).css('border-left', 'solid 3px');",
  "}"
)

DT::datatable(dplyr::select(df_qrt, -year),
              container = sketch_qrt,
              class = 'cell-border',
              rownames = FALSE,
              fillContainer = TRUE, 
              options = list(headerCallback = JS(headerCallback)))

enter image description here

To have another color, do "border-top: solid orange 3px", etc.

Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225