【问题标题】:How to repeat column headers in GT and/or Data.Table in R如何在 GT 和/或 R 中的 Data.Table 中重复列标题
【发布时间】:2021-08-14 02:17:09
【问题描述】:

因此将使用此站点作为数据源 (https://rstudio.github.io/DT/extensions.html)。 mtcars 是嵌入在 R 中的数据源。下面是来自该链接的代码,更具体地说是项目编号 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

【问题讨论】:

    标签: r dplyr row dt


    【解决方案1】:

    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'
    )
    

    它的工作原理是构建一个 &lt;tr&gt; 行,其中包含您想要查看的硬编码标题(以及第一个单元格的摘要行数)。

    最终结果:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-02
      • 1970-01-01
      • 1970-01-01
      • 2015-03-21
      • 2021-11-13
      • 2016-01-20
      • 1970-01-01
      相关资源
      最近更新 更多