Is there a way to group columns into "main" headings using the dt package in r (or even the formattable package for that matter)? I have created an example of what I have been trying to do but cannot seem to find a function for it anywhere. I am making a table for a shiny Web App so it appears I may have to customize the CSS, although I'm not sure that is possible. To be clear, the Historical
and Current
headers are what I would like to replicate in my datatable.
For purposes of example, the following df would be split into two groupings under the same data frame with 1:4 being labelled under Historical
and 5:8 being labelled under Current
.
df <- data.frame(1,2,3,4,5,6,7,8)
Thank you so much.
You could achieve that using Custom Table Container (see here: https://rstudio.github.io/DT/) and some JS (jQuery) to modify table CSS style.
# a custom table container
sketch = htmltools::withTags(table(
class = 'display',
thead(
# Define the grouping of your df
tr(
th(colspan = 4, 'Historical'),
th(colspan = 4, 'Current')
),
# Repeat column names 8 times
tr(
lapply(paste0("Col ", 1:8), th)
)
)
))
# Using JS for adding CSS, i.e., coloring your heading
# Get the corresponding table header (th) from a table cell (td) and apply color to it
headjs <- "function(thead) {
$(thead).closest('thead').find('th').eq(0).css('background-color', '#D9E1F2');
$(thead).closest('thead').find('th').eq(1).css('background-color', '#8EA9DB');
}"
# Your data frame
df <- data.frame(1,2,3,4,5,6,7,8)
# Output DT with your custom header
datatable(df , container = sketch, options = list(
headerCallback = JS(headjs)
))
And the output: