在 R 中使用 DT 包对列进行分组

Grouping Columns with DT Package in R

有没有办法使用 package in (or even the formattable package for that matter)? I have created an example of what I have been trying to do but cannot seem to find a for it anywhere. I am making a table for a Web App so it appears I may have to customize the CSS, although I'm not sure that is possible. To be clear, the Historical and Current headers are what I would like to replicate in my .

将列分组为 "main" 个标题

示例数据Table

例如,以下 df 将在同一数据帧下分成两个组,1:4 标记在 Historical 下,5:8 标记在 [=12 下=].

df <- data.frame(1,2,3,4,5,6,7,8)

非常感谢。

您可以使用自定义 Table 容器(参见此处:https://rstudio.github.io/DT/)和一些 JS (jQuery) 修改 table CSS 样式来实现.

# a custom table container
sketch = htmltools::withTags(table(
  class = 'display',
  thead(
# Define the grouping of your df
    tr(
      th(colspan = 4, 'Historical'),
      th(colspan = 4, 'Current')
    ),
# Repeat column names 8 times
    tr(
      lapply(paste0("Col ", 1:8), th)
    )
  )
))
# Using JS for adding CSS, i.e., coloring your heading
# Get the corresponding table header (th) from a table cell (td) and apply color to it
headjs <- "function(thead) {
  $(thead).closest('thead').find('th').eq(0).css('background-color', '#D9E1F2');
   $(thead).closest('thead').find('th').eq(1).css('background-color', '#8EA9DB');

}"

# Your data frame
df <- data.frame(1,2,3,4,5,6,7,8)

# Output DT with your custom header
datatable(df , container = sketch,  options = list(
  headerCallback = JS(headjs)
))

并且输出: