如何在 R 中的 GT and/or Data.Table 中重复列 headers

How to repeat column headers in GT and/or Data.Table in R

因此打算使用此站点作为数据源 (https://rstudio.github.io/DT/extensions.html)。 mtcars 是嵌入在 R 中的数据源。下面是来自 link 的代码,更具体地说是项目编号 9 或行组。 我的问题是:我将如何拥有专栏; mpg、cyl、disp 等重复并显示在每个轮廓的顶部。例如,我希望列标题 (mpg、cyl、disp) 再次出现,但在这种情况下,它将与 6.

在同一行中
library(DT)
mtcars2 = mtcars[1:20, ]
datatable(
mtcars2[order(mtcars2$cyl), ],
extensions = 'RowGroup',
options = list(rowGroup = list(dataSrc = 2)),
selection = 'none'
)

期望的结果看起来像这样。

6             mpg     cyl      disp
Mazda RX4      21      6        160

DataTables 允许您使用 rowGroup.startRender 选项自定义摘要(分组)行的内容。

翻译成R和DT,看起来是这样的:

library(DT)
mtcars2 = mtcars[1:20, ]
datatable(
  mtcars2[order(mtcars2$cyl), ],
  extensions = 'RowGroup',
  options = list(
    rowGroup = list(
      dataSrc = 2,
      startRender = JS(
        "
        function ( rows, group ) {
          return $('<tr/>')
            .append( '<td>' + rows.toArray()[0].length + '</td>' )
            .append( '<td>mpg</td>' )
            .append( '<td>cyl</td>' )
            .append( '<td>disp</td>' )
            .append( '<td>hp</td>' )
            .append( '<td>drat</td>' )
            .append( '<td>wt</td>' )
            .append( '<td>qsec</td>' )
            .append( '<td>vs</td>' )
            .append( '<td>am</td>' )
            .append( '<td>gear</td>' )
            .append( '<td>carb</td>' );
        }"
      ),
      endRender = NULL
    )
  ),
  selection = 'none'
)

它的工作原理是构建一个 <tr> 行,其中包含您要查看的 hard-coded 个标题(以及第一个单元格的摘要行数)。

最终结果: