7

I would like to get a DataTable (with all its ranking, search and page features) that does not stretch fully across the page, and results in large amounts of white space in each column...

enter image description here

... ideally with column widths similar to the "wrap" style from renderTable...

enter image description here

I know I can fix relative column widths, however, my table will dynamically update with different numbers of columns dependent of inputs selected. I would prefer additional columns to expand into the empty space on the right hand side and then trigger a horizontal scrollbar if it becomes wider than the browser window width.

Reproducible example of the tables in the images above...

library(shiny)
runApp(list(
  ui = navbarPage(
  title = 'Tables',
  tabPanel('dataTableOutput', dataTableOutput('ex1')),
  tabPanel('tableOutput', tableOutput('ex2'))
),
server = function(input, output) {
  output$ex1 <- renderDataTable(iris)
  output$ex2 <- renderTable(iris)
}
))
guyabel
  • 6,849
  • 5
  • 42
  • 76
  • I know it doesn't address your question directly, but RStudio just announced htmlwidgets for R which includes among other cool things, DataTables. http://www.htmlwidgets.org/showcase_datatables.html – Khashaa Dec 19 '14 at 19:06

2 Answers2

8

I think that you should use drawCallback in dataTables. Here I just changed your example a little to fix width of dataTable to 600px. you can play with possible java script function in callback function to do almost anything.

library(shiny)
runApp(list(
  ui = navbarPage(
    title = 'Tables',
    tabPanel('dataTableOutput', dataTableOutput('ex1')),
    tabPanel('tableOutput', tableOutput('ex2'))
  ),
  server = function(input, output) {
    output$ex1 <- renderDataTable( iris, 
                                   option = list( drawCallback = I("function( settings ) {document.getElementById('ex1').style.width = '600px';}")) )
    output$ex2 <- renderTable(iris)
  }
))
Mahdi Jadaliha
  • 1,759
  • 1
  • 12
  • 22
0

Assuming your data.frame is df, then put this code at the beginning of the reactive/renderTable block at the server side. It will wrap the column names to desirable length and therefore reducing the size of the table. You can always change the width to equal the desired width.

library(stringr)

colnames(df) = str_wrap(colnames(df),width = 10)
oldtechaa
  • 1,444
  • 1
  • 15
  • 24