簡體   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