Awais Hassan
Awais Hassan

Reputation: 91

Selecting rows from data table with filter option:RShiny

I have a data table with filter enabled and i want to read selected rows from this data table.

input$table_rows_selected works fine if the filter is not applied however once i apply filter on data then correct rowindex is not returned.

ui <- function(id) {
  fluidPage(
    title = "Job Tracker",

    fluidRow(
      column(width=6,
             selectInput("pickvalue", label = "Pick a Value", choices = unique(iris$Species))
      )
    ),

    br(),
    fluidRow(
      column(12,
             DT::dataTableOutput("job_data")

      )

    ),
    br(),
    fluidRow(
      column(12,DT::dataTableOutput("x4"))
    )
  )

}

server <- function(input, output, session)
{
      output$job_data  <- DT::renderDataTable({
      datatable(iris[iris$Species==input$pickvalue,],selection = "single")
      })

    output$x4 <- DT::renderDataTable({
      s <- input$job_data_rows_selected
      datatable(iris[s,])
    })

}

Upvotes: 2

Views: 4025

Answers (1)

Pork Chop
Pork Chop

Reputation: 29407

To return previously selected row index you can add some reactiveValues to track the index like so, please note that the index is subject to data so if you select index = 4 and switch the data, the index = 4 will be applied to new data:

library(shiny)
library(DT)
ui <- function(id) {
  fluidPage(
    title = "Job Tracker",

    fluidRow(
      column(width=6,
             selectInput("pickvalue", label = "Pick a Value", choices = unique(iris$Species))
      )
    ),

    br(),
    fluidRow(
      column(12,
             DT::dataTableOutput("job_data")

      )

    ),
    br(),
    fluidRow(
      column(12,DT::dataTableOutput("x4"))
    )
  )

}

server <- function(input, output, session){
  v <- reactiveValues()
  v$s <- NULL

  data <- reactive({
    iris[iris$Species==input$pickvalue,]
  })

  output$job_data  <- DT::renderDataTable({
    datatable(data(),selection = "single")
  })

  observe({
    if(!is.null(input$job_data_rows_selected)){
      v$s <- input$job_data_rows_selected
    }
  })

  output$x4 <- DT::renderDataTable({
    datatable(data()[v$s,])
  })
}
shinyApp(ui, server)

enter image description here

If you want to keep the index correctly, remove rownames:

 data <- reactive({
    data <- (iris[iris$Species==input$pickvalue,])
    rownames(data) <- NULL
    data
  })

Upvotes: 5

Related Questions