Search code examples
rdataframeformattingcolumnheader

Table output - grouping column headings for PDF table


I'd like to know if there's any way of effectively grouping column headings when outputting a summary table. I realise that's a terrible explanation of what I want so here's an example.

Let's say I have a summary dataframe with 5 columns: projectName, currMonthCost, currMonthRev, prevMonthCost, prevMonthRev. I'd like to have 2 levels to the column headings, with the final output to group the columns by curr/prev - something like:

               ||     Current    ||    Previous    ||  
  projectName  ||  Cost  |  Rev  ||  Cost  |  Rev  ||
_______________||________|_______||________|_______||
               ||        |       ||        |       ||
       x       ||    x   |   x   ||    x   |   x   ||  
       y       ||    y   |   y   ||    y   |   y   ||

Apologies for the poor attempt at making a table, I'm new here. But hopefully you get the idea.

Is there a package that can handle that? I'm already using formattable but can't find anything obvious in there. I'm happy for it to be a complete botch if there's nothing ready made - it's only summary numbers getting exported to PDF. I just want to avoid having to export to excel to merge cells before PDFing.

Thanks in advance. James


Solution

  • You need the DT library. It's a quite powerful tool for displaying data frames. In your case, you can customize the table headers using the container parameter:

    library(DT)
    
    df <- data.frame(projectName = c("x", "y"), currMonthCost = c("x", "y"), currMonthRev = c("x", "y"), prevMonthCost = c("x", "y"), prevMonthRev = c("x", "y"))
    
    df
    #  projectName currMonthCost currMonthRev prevMonthCost prevMonthRev
    #1           x             x            x             x            x
    #2           y             y            y             y            y
    
    sketch = htmltools::withTags(table(
          class = 'display',
          thead(
              tr(
                  th(rowspan = 2, 'projectName'),
                  th(colspan = 2, 'Current'),
                  th(colspan = 2, 'Previous')
              ),
              tr(
                  lapply(rep(c('Cost', 'Rev'), 2), th)
              )
          )
      ))
    
    datatable(df, container = sketch, rownames = F)
    

    enter image description here