Search code examples
rshinydt

Identify displayed rows


I'm working on an R Shiny App containing a DataTable (myDataTable). There I need three export functions, providing the following functionality:

  1. export all the rows to CSV
  2. export the selected rows to CSV
  3. export the displayed rows to CSV

One and two are easily solved. 1. All entries: I just export the server-side data.frame that serves as the data model for the DataTable. 2. Selected entries: I access selected rows like this:

observeEvent(input$myDataTable_rows_selected, {
    rows <- sort(input$myDataTable_rows_selected)
    # do something with rows
}

But how can I find out which rows are displayed (i.e. filtered)? I thought of an HTML approach, where I select all the tr elements that are childs of div#myDataTable, but shinyjs doesn't offer any useful functions for that.


Solution

  • You can simply use input$myDataTable_rows_all for the filtered data.

    Small example:

    library(shiny)
    library(DT)
    
    shinyApp(
      ui = fluidPage(
        dataTableOutput('myDataTable')
      ),
    
      server = function(input, output) {    
        observeEvent(input$myDataTable_rows_all, {
          rows_filtered <- input$myDataTable_rows_all
          rows_displayed <- rows_filtered[1:min(length(rows_filtered), input$myDataTable_state$length)]
          # Download rows with your download fct.
          print(rows_displayed)
        })
    
        output$myDataTable = DT::renderDataTable({
          datatable(mtcars, options = list(stateSave = TRUE))
        })
      }
    )