Search code examples
rdplyrrowdt

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). mtcars is a datasource embedded in R. Below is the code from that link, more specifically item number 9 or Row Group. 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. 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.

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

Solution

  • DataTables allows you to customize the contents of that summary (grouping) row using the rowGroup.startRender option.

    Translated to R and DT, it looks like this:

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

    The end result:

    enter image description here