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

是否有一种方法可以使用中的包(甚至是formattable包)将列分组为“主要”标题?我已经创建了一个示例,说明了我一直在尝试做的事情,但似乎无法在任何地方找到它的。我正在为 Web App制作一张表,因此似乎不确定是否必须自定义CSS。需要明确的是,HistoricalCurrent标头是我想在中复制的标题。

示例数据表

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

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

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

非常感谢您。

w419537740 回答:在R中使用DT包对列进行分组

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

输出:

enter image description here

本文链接:https://www.f2er.com/2533113.html

大家都在问