40
votes

Using R shiny & DT package, I am creating certain tables. The number of columns vary as per user input & is not fixed. I have included the following code snippet to include a horizontal scrollbar so that when the number of columns is large, the user can scroll through the columns that are not directly visible.

server.R:

output$results <- DT::renderDataTable({
    DT::datatable(data = datasetInput(),
                  options = list(scrollX = TRUE,...)
                  )
  })
<code reduced for brevity>

Using the above code, the Horizontal scrollbar is not visible at first but appears when I click on a row and hit right arrow on my keyboard. Is there any way the scroll bar becomes visible as soon as the table is fired up, no matter how many columns I have, and I can drag the scrollbar using the mouse pointer?

Update:

I tried the code in the answer below and this is what I see - no horizontal scrollbar.

enter image description here

3
Please always provide your sessionInfo(). You didn't say it, but my guess you were using Mac OS X. If that is the case, there is nothing surprising. That is just the default behavior of Mac -- scrollbars are hidden by default until you start scrolling.Yihui Xie
Thanks Yihui. True, I am using MacOSX. I will make sure I provide my sessionInfo() in the future.Komal Rathi
I don't use Mac often, but I guess there might be a way to make the scrollbar always visible. See if you have any luck with Google...Yihui Xie

3 Answers

66
votes

I don't think you can (or should) force a scrollbar easily if you don't need one, but the above code works fine for me, it shows a scrollbar when the page initializes. Maybe the problem is with the data or something else.

Here's a minimal example that has a horizontal scrollbar on page load

runApp(shinyApp(
  ui = fluidPage(
    DT::dataTableOutput("results", width = 300)
  ),
  server = function(input, output, session) {
    output$results <- DT::renderDataTable(
      mtcars,
      options = list(scrollX = TRUE)
    )
  }
))
13
votes

Try this:

DT::datatable(sta, options = list(
  pageLength=50, scrollX='400px'), filter = 'top')
1
votes

I would have done this way also:

datasetInput1 <- reactive({
      infile <- input$file1
      if(is.null(infile))
        return(NULL) 
      else
        m <- read.csv(infile$datapath, header = input$header)
        return ( DT::datatable(m, extensions = 'Scroller', options = list(deferRender = F, dom = 't',
                                                                      columnDefs = list(list(className = 'dt-center',
                                                                                             targets = 5)),
                                                                     scrollY = 300, scroller = TRUE, scrollX = T,
                                                                     pageLength = 5))
               )
    })