繁体   English   中英

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

[英]Grouping Columns with DT Package in R

有没有办法使用包(或者甚至是 formattable 包)将列分组为“主”标题? 我已经创建了一个我一直在尝试做但似乎无法在任何地方找到它的的例子。 我正在为一个Web 应用程序制作一个表格,所以看起来我可能需要自定义 CSS,尽管我不确定这是否可行。 需要明确的是,在HistoricalCurrent头是我想在我的复制什么

示例数据表在此处输入图片说明

出于示例的目的,以下 df 将在同一数据框下分为两组,其中 1:4 标记在Historical下, 5:8 标记在Current下。

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

非常感谢。

您可以使用自定义表格容器(参见此处: https : //rstudio.github.io/DT/ )和一些 JS (jQuery) 来修改表格 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)
))

和输出:

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM