How do I get the data from the selected rows of a filtered datatable (DT)?
<p>The DT package allows you to get the indices of selected rows using <code>input$tableID_rows_selected</code>. This works great for tables that do not have filtered data. However, if we have a filtered dataset, we can't use this same approach, as the row indices are off.</p>

<p>For a filtered dataset, then, how would we get the data in the selected rows of a datatable?</p>

<p>Below, I've posted a basic shiny app that shows four tables: the first one is the original mtcars dataset and the second gets the selected rows in the first. The third and the fourth do the same thing, but after filtering the dataset on the "filter" sliderInput.</p>

<pre><code>library(shiny)
library(DT)
library(dplyr)

ui &lt;- fluidPage(
  DT::dataTableOutput("origTable"),
  DT::dataTableOutput("origTableSelected"),
  sliderInput("filter", label = "Filter by cyl", min = 4, max = 8, step = 2, value = 6),
  DT::dataTableOutput("filteredTable"),
  DT::dataTableOutput("filteredTableSelected")
)


server &lt;- function(input, output, session) {

  output$origTable &lt;- DT::renderDataTable({
    datatable(
      mtcars,
      selection = list(mode = "multiple"),
      caption = "Original Data"
    )
  })

  origTable_selected &lt;- reactive({
    ids &lt;- input$origTable_rows_selected
    mtcars[ids,]
  })

  output$origTableSelected &lt;- DT::renderDataTable({
    datatable(
      origTable_selected(),
      selection = list(mode = "multiple"),
      caption = "Selected Rows from Original Data Table"
    )
  })

  output$filteredTable &lt;- DT::renderDataTable({
    datatable(
      filter(mtcars, cyl == input$filter),
      selection = list(mode = "multiple"),
      caption = "Filtered Table (based on cyl)"
    )
  })

  filteredTable_selected &lt;- reactive({
    ids &lt;- input$filteredTable_rows_selected
    mtcars[ids,]
  })

  output$filteredTableSelected &lt;- DT::renderDataTable({
    datatable(
      filteredTable_selected(),
      selection = list(mode = "none"),
      caption = "Table that gets data from unfiltered original data"
    )
  })
}

shinyApp(ui = ui, server = server)
</code></pre>