6
votes

I am trying to build a shiny app that uses the datatable FixedColumns plugin:

https://datatables.net/extensions/fixedcolumns/

The datasest I am using will have around 100 columns and I want to fix the first five columns and allow the user to scroll through the rest. From the examples it looks like I'd need to use this javascript:

https://datatables.net/release-datatables/extensions/FixedColumns/examples/two_columns.html

$(document).ready(function() {
    var table = $('#example').DataTable( {
        scrollY:        "300px",
        scrollX:        true,
        scrollCollapse: true,
        paging:         false
    } );
    new $.fn.dataTable.FixedColumns( table, {
        leftColumns: 2
    } );
} );

I don't know javascript but in the past I have been able to use I() to insert javascript options. This time though it looks like I need to do something else. I've tried the code below and get the message: "ERROR: 'options' must be a named list'.

library(shiny)
library(ggplot2)
data(diamonds)
hw <- diamonds

runApp(
  list(ui=(
    fluidPage(
      tabsetPanel(
        id = 'dataset',
        tabPanel('hw', dataTableOutput('mytable1'))
      ))),

    server = (function(input, output, session) {
      output$mytable1 <- renderDataTable(
        head(hw, 50), 
        options = list(scrollY = '300px',
                       scrollX = TRUE,
                       scrollCollapse = TRUE,
                       paging = FALSE,

                       I("new $.fn.dataTable.FixedColumns( table, {
                        leftColumns: 5
                        } );")
                       ))


    })

  ))
2
I have had the same problem/ question. I haven't found a clear explanation of how to do this/ example anywhere so far.numbercruncher

2 Answers

0
votes

In case anyone comes across this question more recently, you can now use the FixedColumns extension directly without any javascript:

https://rstudio.github.io/DT/extensions.html

m = as.data.frame(round(matrix(rnorm(100), 5), 5))
datatable(
  m, extensions = 'FixedColumns',
  options = list(
    dom = 't',
    scrollX = TRUE,
    fixedColumns = TRUE
  )
)
-1
votes
list(tags$head(tags$script('type = "text/javascript"', '
        $(document).ready( function () {
            var table = $("#example").DataTable( {
                "scrollY": "300px",
                "scrollX": "100%",
                "scrollCollapse": true,
                "paging": false
            } );
            new $.fn.dataTable.FixedColumns( table );
        } );
')))