Select rows with same values in two columns in datatable (DT)


#1

Hello All,

I have an app in which the user can select multiple rows of a data table and export them into another table. The idea is, that if user select the first row with “cyl” value 6 and “gear” value 4 than all rows with the same “cyl” and “gear” values are selected.

The problems are that it’s not possible to deselect rows and when filters are changed then wrong rows are reselected. Any help would be greatly appreciated.

library(shiny)
library(DT)
library(dplyr)
library(data.table)

shinyApp(
  ui <- fluidPage(
    fluidRow(
      column(4, br(),
             selectInput("cyl", "Cylinders", 
                         choices = NULL, multiple = TRUE),
             selectInput("gear", "Gears", 
                         choices = NULL,multiple = TRUE),
             selectInput("carb", "carb", 
                         choices = NULL, multiple = TRUE)
      ),
      column(8, br(), DT::dataTableOutput("mainTable")
      )
    )
  ),
  
  server <- function(input, output, session) { 
    
    tobedropped <- reactiveValues(drop = NULL)
    
    carsDat <- mtcars
    
    ## updating drop-down lists ####
    observe({
      updateSelectInput(session, "cyl","cyl", choices = unique(carsDat$cyl))
      updateSelectInput(session, "gear","gear", choices = unique(carsDat$gear))
      updateSelectInput(session, "carb","carb", choices = unique(carsDat$carb))
    })
    
    ## subsetting data, main table
    output$mainTable <- DT::renderDataTable( {
      datSub <- carsDat %>%
        filter(cyl %in% input$cyl, gear %in% input$gear, carb %in% input$carb) %>%
        select(cyl, gear, carb, mpg)
      
      
      datSelect <- as.data.table(datSub[input$mainTable_rows_selected, ])
      
      tobedropped$drop <- unique(rbind(tobedropped$drop, datSelect[ ,c("cyl", "gear")]))
      
      rownumb <- which(data.table(datSub)[ ,paste(cyl, gear)] %in% tobedropped$drop[ ,paste(cyl, gear)])
      
  
      DT::datatable(datSub, selection =  list(mode = 'multiple', selected = rownumb, target = 'row'))
    })
  }
)