rdt

Create sub headers in DT datatable


I have this dataframe and I want to create a DT datatable which will have sub headers like Gender and Race like the image below. How can I do it using DT ?

# Create the dataframe using data.frame
df <- data.frame(
  attribute = c("male", "female", "hispanic", "african"),
  value1 = c(10, 20, 30, 40),
  value2 = c(50, 60, 70, 80)
)
library(DT)
datatable(df)

enter image description here


Solution

  • I would agree with previous comment that DT may not be the best approach. If you really need to use it, then there is the RowGroup extension which provides this type of formatting. You can create the headers in your data, then use them as follows:

    # create a new column with the header items
    df$header <- c("Gender", "Gender", "Ethnicity", "Ethnicity")
    
    # use the RowGroup extension to apply this to the table (also don't show this column as data)
    datatable(df,
              extensions = "RowGroup",
              options = list(
                             rowGroup = list(dataSrc = c(4)),                     # use the header column as row headers (`header` is the 4th column here)
                             columnDefs = list(list(visible=FALSE, targets=c(4))))  # hide the header column from the data
    
    )
    
    

    result