Search code examples
rshinydt

Render Data Table with double header


I have the following table:

df <- data.frame(MUSIC_TYPE=c("Pop","Rock","Blues"),A=c(200,80,98),B=c(100,217,70),Cc(80,120,200))
colnames(df) <- c("MUSIC_TYPE","70s","80s","90s")

I would need to show this (simplified) table as a Render Data Table. The header by default will be the name of each column, and that's ok. However, I would need a first additional header showing the following "VINTAGE". I attach a screenshot to show what I mean. enter image description here

I read and saw this example https://rstudio.github.io/DT/ but I'll be honest and I don't understand how to apply it to my case. In that example, all the columns contain the word "Length" and "Width". In my case, is there any easier way to simply add a one row header? This is what I have so far:

df <- datatable(df, 
                  filter = 'none',
                  rownames= FALSE,
                  options = list(scrollX = F
                                 #, dom = 'ft'
                                 , lengthChange = T
                                 , pagingType = "numbers"  # this hides the Next and Previous buttons -->  https://datatables.net/reference/option/pagingType
                                 , autoWidth = T
                                 , pageLength = 5 # this determines how many rows we want to see per page
                                 , info = FALSE #  this will hide the "Showing 1 of 2..." at the bottom of the table -->  https://stackoverflow.com/questions/51730816/remove-showing-1-to-n-of-n-entries-shiny-dt
                                 ,searching = FALSE  # this removes the search box  ->  https://stackoverflow.com/questions/35624413/remove-search-option-but-leave-search-columns-option
                  ))

Solution

  • Adapting the provided example :

    # a custom table container
    sketch = htmltools::withTags(table(
      class = 'display',
      thead(
        tr(
          th(colspan = 1, ''),
          th(colspan = 3, 'Vintage')
        ),
        tr(
          lapply(colnames(df), th)
        )
      )
    ))
    
    DT::datatable(df, container = sketch, ...
    

    enter image description here