Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save sorting in dataTable in shiny?

I have table on page with possible sorting in columns, by after I reload data with reactive table isn't sorted again, here the server.R code:

    library(shiny)

shinyServer(function(input, output) {

  # Return the requested dataset
  datasetInput <- reactive({
    switch(input$dataset2,
           "[,...]" = diamonds,
           "[10:30,...]" = diamonds,
           "[31:50,...]" = diamonds)
  })

  #"[,...]" = diamonds[,],
  #"[10:30,...]" = diamonds[10:30,],
  #"[31:50,...]" = diamonds[31:50,])

  # Show the first "n" observations
  output$view <- renderTable({
    head(datasetInput())
  })

  # a large table, reative to input$show_vars
  output$mytable1 <- renderDataTable({
    library(ggplot2)
    datasetInput()[, input$show_vars, drop = FALSE]
  })

})
like image 775
roman-v1 Avatar asked Jan 15 '15 14:01

roman-v1


1 Answers

The best way to retain sort order (and selection) is to use proxyDataTable and replaceData to update your data, rather than creating a new table each time the data is updated:

mydata = reactive({
    df$ID <<- c(df$ID[n], df$ID[-n])
    df
  })
  output$foo = DT::renderDataTable(isolate(mydata()))
  proxy = dataTableProxy('foo')

  observe({
    replaceData(proxy, mydata(), resetPaging = FALSE)
  })

There are a couple things to be aware of though. If you are using modules, check out this thread to make sure you are passing the right session variable to the proxy: https://github.com/rstudio/DT/issues/359

Also, if you use rownames=false for your datatable, you must also pass the parameter to replaceData.

If proxyDataTable is not an option, you can also use callbacks in DT::renderDataTable:

#include some javascript
tags$head(tags$script(src="my.js"))

#options to renderDataTable
 preDrawCallback = JS("initTableOrder"),
 drawCallback = JS("saveTableOrder")

The javascript functions in my.js (stored in your www directory):

var tableSortOrderSave;

function initTableOrder(settings, json) {   
  if(tableSortOrderSave === undefined){
    $(this.api().table().order());
  }else{
    $(this.api().table().order(tableSortOrderSave));
  }
}

function saveTableOrder(settings, json) {
  order  = $(this.api().table().order());
  if(order.length > 0){
    tableSortOrderSave = order;
  }
}
like image 157
michael Avatar answered Oct 10 '22 17:10

michael