How to keep row from datatable selected even when the table is filtered with selectedinputs

Hi,

With shiny, I work on a datable with multiple row selection. I also have a selectedinput to filter this datable by category (in the example "species"). The problem I encounter is that each time I select a different species I loose the previous row selection. I would like to keep these rows selected even if they don't appear on the datatable that has been filtered. In other words, previously selected rows should be deselected only when I click on the rows or on a specific button.

You will find below the code I am working on.

Hope it is clear and thanks for your help!


library(shiny)
library(DT)
library(sbtools)
library(reactable)
library(shinyjs)


ui <- fluidPage(
                sidebarPanel(selectInput(inputId = "species", label = ("Species"),choices = c("All",unique(as.character(iris$Species)))
                ),uiOutput("SelectedSpecies")), 
                mainPanel(dataTableOutput("mytable"))
                
)


server <- function(input, output,session) {
  
  
  newdata <- reactive({
    
    if (input$species=="All") {
      filtered_data <- iris

    } else {
      filtered_data<-iris
      filtered_data <- subset(iris,iris$Species==input$species)
    
    }
    
    return(filtered_data)
    
  })
  
  
  output$mytable =renderDataTable({
    
    output_table<-newdata()
    
    datatable(output_table,selection = list(mode = 'multiple'))
    
  })
  
  
  selection <- reactive ({
    input$mytable_rows_selected
  })
  
  
  output$SelectedSpecies <- renderUI({
    
    row_selected<-selection()
    
    checkboxGroupInput("SelectedSpecies", label = "Selected Species", 
                       choices = rownames(newdata())[as.numeric(row_selected)],selected = rownames(newdata())[as.numeric(row_selected)])
  })  

  
}

shinyApp(ui, server)

```