Reorder data table with seleceted rows first


#1

Hello. I have developed an app in which the user can select multiple rows of a data table to view in a heatmap. The problem is that because the data table is so large, keeping track of which rows were searched for and selected is difficult. Is there a way to display the selected rows at the top of the data table so it is easier to deselect them?


#2

One can achieve this with the help of DT::replaceData() and DT::selectRows(). I’ve attached a small example where one can click on a button to show the selected rows at the beginning of the table. I hope this helps for your problem.

library(shiny)
library(DT)

shinyApp(
  ui = fluidPage(
    fluidRow(
      column(2, actionButton("but_sortSelectedFirst", "Selected Rows First")),
      column(10, DT::dataTableOutput('foo'))
    )
  ),
  server = function(input, output, session) {
    data <- reactiveValues(table_data = iris)
    
    observeEvent(input$but_sortSelectedFirst, {
      # the selected rows are in the variable input$tableid_rows_selected
      selected_rows <- input$foo_rows_selected
      
      # calculate new row order
      row_order <- order(
        seq_along(cars[[1]]) %in% selected_rows,
        decreasing = TRUE
      )
      data$table_data <- data$table_data[row_order, ]
      
      proxy <- DT::dataTableProxy('foo')
      DT::replaceData(proxy, data$table_data)
      # make sure to select the rows again
      DT::selectRows(proxy, seq_along(selected_rows))
    })
    
    output$foo <- DT::renderDataTable(isolate(data$table_data))
  }
)

#3

Thank you, mgirlich! worked great


#4

If you question has been answered, do you mind accepting the post that solved your problem? Thanks!

You can see this post by @mara about how to accept an answer: