我们可以使用自定义容器将列组名称添加为真实的列标题:
# ui.R
ui <- fluidPage(
DT::dataTableOutput("table")
)
# server.R
library(DT)
df <- data.frame(A = c(1, 1, 1), B = c(1, 1, 1), C = c(1, 1, 1),
D = c(2, 2, 2), E = c(2, 2, 2), F = c(2, 2, 2),
G = c(3, 3, 3), H = c(3, 3, 3), I = c(3, 3, 3))
myContainer <- htmltools::withTags(table(
class = 'display',
thead(
tr(
th(),
th(colspan = 3, 'Trial 1', class = "dt-center"),
th(colspan = 3, 'Trial 2', class = "dt-center"),
th(colspan = 3, 'Trial 3', class = "dt-center")
),
tr(
th(),
lapply(names(df), th)
)
)
))
server <- function(input, output) {
output$table <- DT::renderDataTable({
DT::datatable(df, container = myContainer,
options = list(dom = "t", ordering = FALSE,
columnDefs = list(list(className = "dt-center", targets = "_all"))
))
})
}
runApp(list(ui = ui, server = server))
Output:
或者,如果您确实希望第一行有 colspan,我们可以使用initComplete
呈现表格时调用 JavaScript 函数的选项。这里仅是服务器部分:
jsc <- '
function(settings, json) {
$("td:contains(\'Trial\')").attr("colspan", "3").css("text-align", "center");
$("tbody > tr:first-child > td:empty").remove();
}'
server <- function(input, output) {
output$table <- DT::renderDataTable({
df <- data.frame(A = c("Trial 1", 1, 1, 1), B = c("", 1, 1, 1), C = c("", 1, 1, 1),
D = c("Trial 2", 2, 2, 2), E = c("", 2, 2, 2), F = c("", 2, 2, 2),
G = c("Trial 3", 3, 3, 3), H = c("", 3, 3, 3), I = c("", 3, 3, 3))
DT::datatable(df, options = list(dom = "t", ordering = FALSE, initComplete = JS(jsc)))
})
}
在 JS 函数的第一行中,我们选择包含该单词的所有单元格Trial并添加相应的属性和样式。然后,我们选择所有空单元格,它们是行元素的直接后代,而行元素又是表主体的第一个子元素,并将它们从 DOM 中删除。Here https://www.w3schools.com/cssref/css_selectors.asp您可以找到有关 CSS 选择器的一般参考,例如>
.
Output: