Applying multiple filters for a reactive table


#1

I’m wondering if anyone could suggest a better (and more scalable) approach to the example below. In general, I’m looking to apply multiple different filters to a data frame, which will then be rendered. On initial load, the filters will be empty so the full data frame will be returned. As inputs, that will be used as filters, are filled in they are applied to the data frame. I’ve accomplish this will various if statements to check for inputs but this doesn’t seem like the most elegant solution as the number of inputs grows.

library(shiny)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

# quick data processing
mtcarsDf <- mtcars %>%
    mutate(car_name = row.names(mtcars)) %>%
    select(car_name, cyl, mpg, gear)

ui <- fluidPage(
    titlePanel(""),
    
    sidebarLayout(
        sidebarPanel(
            textInput("name",
                      "Name"),
            selectInput("gear",
                        "Gears",
                        choices = mtcarsDf$gear
            ),
            selectInput("cyl",
                        "Cycles",
                        choices = mtcarsDf$cyl)
        ),
        mainPanel(
            DT::dataTableOutput("table"),
            plotOutput("plot")
        )
    )
)

server <- function(input, output, session) {
    
    reactiveDf <- reactive({
        if (input$name == "" &
            input$cyl == "") {
            return(mtcarsDf)
        }
        
        if (input$name != "") {
            mtcarsDf <- mtcarsDf %>%
                filter(
                    grepl(input$name, car_name, ignore.case = TRUE)
                )
            
        }
        
        if (input$cyl != "") {
            mtcarsDf <- mtcarsDf %>%
                filter(
                    cyl == input$cyl
                )
            
        }
        
        return(mtcarsDf)
    })
    
    output$table <- DT::renderDataTable({
        reactiveDf()
    })
    
}

shinyApp(ui, server)