简体   繁体   English

如何在 R 中重复 GT 和/或 Data.Table 中的列标题

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

So going to use this site as the datasource ( https://rstudio.github.io/DT/extensions.html ).所以要使用这个站点作为数据源( https://rstudio.github.io/DT/extensions.html )。 mtcars is a datasource embedded in R. mtcars 是嵌入在 R 中的数据源。 Below is the code from that link, more specifically item number 9 or Row Group.以下是该链接中的代码,更具体地说是项目编号 9 或行组。 My question is this: How would I have the columns;我的问题是:我将如何拥有这些专栏; mpg, cyl, disp, etc. to repeat and show up on at the top of every delineation. mpg、cyl、disp 等重复并显示在每个轮廓的顶部。 For example, I would want the column titles (mpg,cyl,disp) to appear a second time but in this case it would be in the same row as 6.例如,我希望列标题 (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'
)

The desired result would look something like this.期望的结果看起来像这样。

6             mpg     cyl      disp
Mazda RX4      21      6        160

DataTables allows you to customize the contents of that summary (grouping) row using the rowGroup.startRender option. DataTables 允许您使用rowGroup.startRender选项自定义该摘要(分组)行的内容。

Translated to R and DT, it looks like this:翻译成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'
)

It works by building a <tr> row containing the hard-coded headings that you want to see (along with the summary row count for the first cell).它的工作原理是构建一个<tr>行,其中包含您想要查看的硬编码标题(以及第一个单元格的摘要行数)。

The end result:最终结果:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM