rshinydt

Get selected row value instead of number


I know I can access selected rows by input$dfname_rows_selected it gives back the numbers of rows selected, but how do I read the rows names, not numbers? In my case they are generated not in the order I use them later, therefore I need to get the values inside to make it work.

ui <- shinyUI(fluidPage(

  DT::dataTableOutput("table"),
  actionButton("btn", "press me")
  
))

server <- function(input, output) {
  observeEvent(input$btn, {
    print(input$table_rows_selected)
  })
  
  output$table <- DT::renderDataTable({
    
    mtcars %>%
      datatable(selection = "multiple")
    
  })
  
}
shinyApp(ui = ui, server = server)

Solution

  • Something like this:

    library(shiny)
    library(DT)
    
    ui <- basicPage(
      mainPanel(DT::dataTableOutput('mytable')),
      textOutput("selected")
    )
    
    server <- function(input, output,session) {
    
      mydata <- reactive({mtcars})
    
      output$mytable = DT::renderDataTable(    
        datatable(mydata())
      ) 
    
      selectedRow <- eventReactive(input$mytable_rows_selected,{
        row.names(mtcars)[c(input$mytable_rows_selected)]
      })
    
      output$selected <- renderText({ 
        selectedRow()
      })
    }
    runApp(list(ui = ui, server = server))