Kasia Kulma
Kasia Kulma

Reputation: 1732

R: Aligning nested headers in DT table

I want to produce a DT table with triple-nested headers but I'm not getting the alignment right. Things are very straightforward with double-nesting, see the code below:

library(DT)
library(dplyr)

### yearly breakdown

df_year <- data.frame(
  group = LETTERS[1:6],
  year = rep(2017, 6),
  A_2017 = rnorm(6),
  B_2017 = rnorm(6)
)

sketch_year = htmltools::withTags(table(class = 'display',
                                   thead(tr(
                                     th(rowspan = 2, 'Group'),
                                     lapply(unique(df_year$year),
                                            th, colspan = 2)
                                   ),

                                   tr(
                                     lapply(rep(c(
                                       'Alpha', 'Beta'
                                     ), length(unique(df_year$year))), th)
                                   ))))

DT::datatable(select(df_year, -year),
              container = sketch_year,
              rownames = FALSE,
              fillContainer = TRUE)

However, if I try to apply similar principles to the third row, it appears misaligned:

## 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(rowspan = 2, 'Group'),
          lapply(unique(df_qrt$year),
                 th, colspan = 8)
        ),
        tr(
          lapply(paste0('Q', 1:4),
                 th, colspan = 2)
        ),

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

DT::datatable(select(df_qrt, -year),
              container = sketch_qrt,
              rownames = FALSE,
              fillContainer = TRUE)

How can I make it align properly? Thanks.

Upvotes: 1

Views: 259

Answers (1)

JABedford
JABedford

Reputation: 103

The alignment is being thrown out, in this case, by the "Group" header not being changed to span the newly created row.

sketch <-  htmltools::withTags(
        table(class = 'display',
              thead(tr(
                th(rowspan = 3, 'Group'),
                lapply(unique(df$year),
                       th, colspan = 8)

Upvotes: 1

Related Questions