【问题标题】:Grouping Columns with DT Package in R在 R 中使用 DT 包对列进行分组
【发布时间】:2020-07-13 15:19:50
【问题描述】:

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

示例数据表

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

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

非常感谢。

【问题讨论】:

    标签: dt r function shiny datatable r datatable dt formattable


    【解决方案1】:

    您可以使用自定义表格容器(参见此处: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)
    ))
    

    还有输出:

    【讨论】:

    • 嗨,米哈!我一直在使用你的代码。标题是否应该自动居中,还是我们明确指定的?
    • @Serkan,默认情况下不对齐标题,字符标题左对齐,数字列始终右对齐。由于表格单元跨越四列(colspan 参数),“历史”和“当前”居中。
    • 哦!谢谢你的澄清!那么如何将标题居中对齐?你能在这里回答这个问题,还是我应该发布一个问题?
    • datatable(df , container = sketch, options = list(headerCallback = JS(headjs), columnDefs = list(list(className = 'dt-center', targets = "_all"))))
    • 谢谢你!我会尽快测试的。
    猜你喜欢
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-12
    相关资源
    最近更新 更多