我想生成一个带有三层嵌套标题的DT
表,但是对齐不正确。双重嵌套非常简单,请参见下面的代码:
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)
但是,如果我尝试将相似的原理应用于第三行,则它似乎未对齐:
## 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)
如何使其正确对齐?谢谢。
答案 0 :(得分:1)
在这种情况下,由于未更改“ Group”标头以覆盖新创建的行,因此导致对齐失败。
sketch <- htmltools::withTags(
table(class = 'display',
thead(tr(
th(rowspan = 3, 'Group'),
lapply(unique(df$year),
th, colspan = 8)