rdt

How to display HTML in DT header?


I would like to put some HTML in the headers of a DT datatable. All my attempts have failed: the tags are rendered "as is". Here is a reproducible example:

> dput(dd)
structure(list(plate = c("P1", "P1", "P1"), row = c(1, 2, 3), 
    Rsquared0 = c("0.3", "45.8", "11.7"), Rsquared1 = c("0.3", 
    "51.1", "20.3"), adjRsquared1 = c("-21.8", "40.2", "2.6"), 
    pvalue = c("99.8", "35.2", "35.1")), .Names = c("plate", 
"row", "Rsquared0", "Rsquared1", "adjRsquared1", "pvalue"), row.names = c(NA, 3L), class = "data.frame")

library(DT)
sketch = htmltools::withTags(
  table(
    class = "display",
    thead(
      tr(
        th(colspan = 2, "Factors"),
        th(colspan = 4, "Statistics")
      ),
      tr(
        lapply(c(names(results)[1:2], 
                 "<i>R</i><sup>2</sup> linear",
                 "<i>R</i><sup>2</sup> quadratic",
                 "adj. <i>R</i><sup>2</sup> quadratic",
                 "<i>p</i> quadratic term"
        ), th)
      )
    )
  )
)

datatable(dd, container = sketch, escape = FALSE)

enter image description here


Solution

  • See ?htmltools::tags: as to use raw HTML, you need HTML. For instance,

    lapply(lapply(c(names(results)[1:2], 
                    "<i>R</i><sup>2</sup> linear",
                    "<i>R</i><sup>2</sup> quadratic",
                    "adj. <i>R</i><sup>2</sup> quadratic",
                    "<i>p</i> quadratic term"
    ), HTML), th)
    

    enter image description here