2

I want to create some tables in a Rmd using DT::datatable. At the moment my table looks like this: enter image description here

But I would prefer to have a header above the colums, so it would say "Pre" on the first ligne and M and SD for Pre under it. This is an example: enter image description here

Can someone help?

Lea
  • 83
  • 1
  • 8

2 Answers2

4

If you did want to use DT::datatable, you could try a solution as suggested in this answer here. This involves creating a "sketch" of the HTML table to be filled with data cells.

library(DT)
library(htmltools)

cont <- withTags(
  table(
    class = "display",
    thead(
      tr(
        th(colspan = 2, "Pre"),
        th(colspan = 2, "Post")
      ),
      tr(
        th("M"),
        th("SD"),
        th("M"),
        th("SD")
      ),
    )
  )
)

datatable(df, rownames = FALSE, container = cont, 
          options = list(
            columnDefs = list(
              list(targets = "_all", className = "dt-center")
            )
          ))

Data

df <- structure(list(Pre_M = c(60.23, 59.96, 60.48), Pre_SD = c(8.02, 
7.98, 8.04), Post_M = c(55.15, 56.48, 53.91), Post_SD = c(9.94, 
10.16, 9.55)), class = "data.frame", row.names = c(NA, -3L))

enter image description here

Ben
  • 28,684
  • 5
  • 23
  • 45
2

If the interactivity of the DT::datatable is not important to you (as the brevity of the table suggests), I would recommend using KableExtra::kable which can easily handle such headers in both HTML and Latex: https://cran.r-project.org/web/packages/kableExtra/vignettes/awesome_table_in_html.html.

persephone
  • 380
  • 2
  • 10