2
votes

I have a data.frame that I want to print in an RMarkdown document (HTML output) in a formatted way. There are 3 features I need for it which I haven't been able to get at the same time:

  1. It needs to have a title or caption at the top to explain what it is.
  2. Since it may be very long, I want it to be scrollable or paged
  3. The caption and column headers should always be visible at the top, even when the table is scrolled or paged

I can get the caption with scrolling easily with kableExtra:

library(kableExtra)
cars %>%
    kable(caption = 'Cars') %>%
    kable_styling(bootstrap_options = c('striped', 'condensed')) %>%
    scroll_box(width = "500px", height = "200px")

But when I scroll down, the caption and column headers scroll too, and it's hard to see what each column is.


By adding df_print: paged to the YAML header, I can get a really nice looking paged output (see R Markdown: The Definitive Guide) from the default printing behavior:

---
title: "Motor Trend Car Road Tests"
output:
  html_document:
    df_print: paged
---

```{r}
cars
```

But, so far as I know, there is no way to put a title or caption on this. I could just add a title using markdown, but then the code to generate the table would be stuck between the title and the table. Any other options that I'm missing?

1

1 Answers

3
votes

I would suggest trying DT::datatable, which produces highly configurable tables in html output.

The following code will create a scrollable table with a fixed header.

DT::datatable(mtcars, 
         extensions = c('FixedColumns',"FixedHeader"),
          options = list(scrollX = TRUE, 
                         paging=FALSE,
                         fixedHeader=TRUE))