DT white space when saving to HTML in R

Viewed 140

I'm using DT to build an HTML table and I keep having this massive white space and can't seem to sort out how to get the columns to strength the page. An additional side note is that my left column fix doesn't seem to be fixing when setting scrollX = TRUE.

Here is an example:

library(tidyverse)
library(DT)

iris %>%
  group_by(Species) %>%
  mutate(across(.cols = c(2:4),
                list(avg = mean, SD = sd))) %>%
  relocate(Species, before = "Sepal.Length") %>%
  datatable(filter = 'top',
            options = list(pageLength = 100,
                          autoWidth = TRUE,
                          scrollY = "800px",
                          scrollX= TRUE,
                          fixedColumns = list(leftColumns = 0)))

enter image description here

1 Answers

The reason isn't because of the datatable itself, it's because of the way that RStudio saves the file.

You can read about the sizingPolicy, as RStudio interprets it here: https://github.com/rstudio/rstudio/blob/master/src/cpp/session/modules/NotebookHtmlWidgets.R

The best way I found to fix this is to set the table to an object and change the object. I couldn't find what I was looking for via datatable's constructs.

This method worked for me:

# Your code, but assigned to d
library(tidyverse)
library(DT)

d <- iris %>%
  group_by(Species) %>%
  mutate(across(.cols = c(2:4),
                list(avg = mean, SD = sd))) %>%
  relocate(Species, before = "Sepal.Length") %>%
  datatable(filter = 'top',
            elementId = "dt",
            options = list(pageLength = 100,
                           autoWidth = TRUE,
                           scrollY = "800px",
                           scrollX= TRUE,
                           fixedColumns = list(leftColumns = 0)))

This will set the table to as wide as your browser window and dynamically adjust if you change the browser window size.

d$sizingPolicy$browser$defaultWidth = "100%"
Related