'Muliple table captions in DT in R

I'm following the example from here: https://rstudio.github.io/DT/

I can get a caption above the table with:

library(DT)

datatable(
  head(iris),
  caption = 'Table 1: This is a simple caption for the table.'
)

And a caption below the table with:

library(DT)

datatable(
  head(iris),
  caption = htmltools::tags$caption(
    style = 'caption-side: bottom; text-align: center;',
    'Table 2: ', htmltools::em('This is a simple caption for the table.')
  )
)

How could I have two captions (above and below) at the same time?

Cheers, Kate



Solution 1:[1]

You can do as follows:

library(DT)

js <- c(
  "function(settings){",
  "  var datatable = settings.oInstance.api();",
  "  var table = datatable.table().node();",
  "  var caption = 'ANOTHER CAPTION'",
  "  $(table).append('<caption style=\"caption-side: bottom\">' + caption + '</caption>');",
  "}"
)

datatable(
  head(iris),
  options = list(
    drawCallback = JS(js)
  ),
  caption = 'Table 1: This is a simple caption for the table.'
)

enter image description here

Solution 2:[2]

Good use of JS() to append a new caption after generation of the table. When I used this with tables that had pagination, the caption would append each time a different page of the data table was selected. To avoid the continuous appending, I would suggest using 'initComplete' instead of 'drawCallback' as the option. Drawing from Stephane Laurent's code:

library(DT)

js <- c(
  "function(settings){",
  "  var datatable = settings.oInstance.api();",
  "  var table = datatable.table().node();",
  "  var caption = 'ANOTHER CAPTION'",
  "  $(table).append('<caption style=\"caption-side: bottom\">' + caption + '</caption>');",
  "}"
)

datatable(
  head(iris),
  options = list(
    initComplete = JS(js) #This will avoid looping of the caption when there is pagination
  ),
  caption = 'Table 1: This is a simple caption for the table.'
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stéphane Laurent
Solution 2