kate88
kate88

Reputation: 371

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

Upvotes: 5

Views: 4209

Answers (2)

PeterI
PeterI

Reputation: 49

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.'
)

Upvotes: 1

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84599

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

Upvotes: 11

Related Questions