简体   繁体   English

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

[英]Grouping Columns with DT Package in R

Is there a way to group columns into "main" headings using the package in (or even the formattable package for that matter)?有没有办法使用包(或者甚至是 formattable 包)将列分组为“主”标题? 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.我正在为一个Web 应用程序制作一个表格,所以看起来我可能需要自定义 CSS,尽管我不确定这是否可行。 To be clear, the Historical and Current headers are what I would like to replicate in my .需要明确的是,在HistoricalCurrent头是我想在我的复制什么

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

For purposes of example, the following df would be split into two groupings under the same data frame with 1:4 being labelled under Historical and 5:8 being labelled under Current .出于示例的目的,以下 df 将在同一数据框下分为两组,其中 1:4 标记在Historical下, 5:8 标记在Current下。

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

Thank you so much.非常感谢。

You could achieve that using Custom Table Container (see here: https://rstudio.github.io/DT/ ) and some JS (jQuery) to modify table CSS style.您可以使用自定义表格容器(参见此处: 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)
))

And the output:和输出:

在此处输入图片说明

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

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