tfr950
tfr950

Reputation: 422

Save filtered DT::datatable into a new dataframe R shiny

Let's say that I have a shiny app displaying a data table like the following:

library(shiny)
library(tidyverse)
library(datasets)
library(DT)

data<- as.data.frame(USArrests)
#data<- cbind(state = rownames(data), data)
ui <- fluidPage(
    dataTableOutput("preview")
)

# Define server logic required to draw a histogram
server <- function(input, output) {

    output$preview<- renderDataTable(
        datatable(data, options = list(searching = T, pageLength = 10, lengthMenu = c(5,10,15, 20), scrollY = "600px", scrollX = T ))
    )
    
}

# Run the application 
shinyApp(ui = ui, server = server)

Let's say I then type in "Iowa" into the search box. I would like to save that filtered datatable into a seperate dataframe within the app. I would like it to be dynamic as well so if I typed "Kentucky", it would save Kentucky's filtered data into the dataframe instead. Is there a way to do this? NOTE: this is a DT datatable

Upvotes: 2

Views: 922

Answers (1)

jpdugo17
jpdugo17

Reputation: 7106

Maybe this type of solution. It is possible to add further conditions like checking the first letter in upper case, but the main idea is to check each column and search for the pattern entered inside the datatable searchbox. This may or may not result in more than one dataset to print (depending if the string is partially matched in multiple columns (this is also solvable with rbind function.

code:

library(shiny)
library(tidyverse)
library(datasets)
library(DT)
data <- as.data.frame(USArrests)
data <- cbind(state = rownames(data), data)
ui <- fluidPage(
  dataTableOutput("preview"),
  tableOutput('filtered_df')
)

# Define server logic required to draw a histogram
server <- function(input, output) {
  
  df <- reactiveValues()
  
  output$preview<- renderDataTable(
    datatable(data, options = list(searching = T, pageLength = 10, lengthMenu = c(5,10,15, 20), scrollY = "600px", scrollX = T ))
  )
 
  observeEvent(input$preview_search, {
   searched_string <- map(data, ~str_subset(.x, input$preview_search)) %>% discard(~length(.x) == 0)  
   
   df$filtered <- syms(names(data)) %>%
                   map(~ filter(data, !!.x %in% searched_string)) %>%
                   discard(~ nrow(.x) == 0)
   
   
   
  })
  
  output$filtered_df <- renderTable({df$filtered})
  
}

# Run the application 
shinyApp(ui = ui, server = server)

Upvotes: 1

Related Questions