Skip to contents

Provides functionality to generate filter inputs dynamically and apply selected filters to a dataset.

Usage

display_filters(filter_df)

filter_data(filter_df, input)

attach_filter(x)

Arguments

filter_df

A data frame containing the data to be filtered.

input

A Shiny input object containing user-selected values for each filter.

x

Character value.

Value

A filtered data frame containing only rows matching the user's filter selections.

Examples


if (interactive()) {

library(shiny)
library(shinyjs)
library(shinyWidgets)
library(dplyr)
library(tidyr)

## Sample filter data

n_resp <- 15
example_df <- tibble(
  id = seq_len(n_resp),
  weight = runif(n_resp, 0.2, 2),
  category = factor(sample(c("A", "B", "C"), n_resp, replace = TRUE)),
  region = factor(sample(
    c("North", "South", "East", "West"), n_resp, replace = TRUE
  )),
  `s_race:White` = sample(c(T, F), n_resp, replace = T),
  `s_race:Black` = sample(c(T, F), n_resp, replace = T),
  `s_race:Asian` = sample(c(T, F), n_resp, replace = T)
) |>
  mutate(
    c_specific_filter = factor(sample(c("C1", "C2"), n_resp, replace = TRUE)),
    c_specific_filter = if_else(category == "C", c_specific_filter, NA),

    ## Show only select levels in a column?
    c_specific_filter =  set_show_only(c_specific_filter, c("C1", "C2")),

    ## Conditional Panel logic
    ## id is set to `c_specific_div` and in the server side, we can use this
    ## id to reset values based on condition.
    c_specific_filter =  set_conditional_panel(
      c_specific_filter,
      condition = glue::glue("(input.{attach_filter('category')} || []).includes('C')"),
      id = "c_specific_div"
    )
  ) |>
  create_filter_data(id_col = id, weight_col = weight)


## Basic app showing how to use a filter_data class
ui <- fluidPage(
  shinyjs::useShinyjs(),
  titlePanel("Filter Example"),
  sidebarLayout(
    sidebarPanel(
      h3("Select Filters"),
      display_filters(example_df)
    ),
    mainPanel(
      fluidRow(
        column(6, h3("Main Table"), tableOutput("main_table")),
        column(6, h3("Filtered Table"), tableOutput("filtered_table"))
      )
    )
  )
)

server <- function(input, output, session) {
# whenever category changes, reset the C-specific picker if C isn't selected
observeEvent(input$filter_category, {
  if (!"C" %in% input$filter_category) {
  shinyjs::reset("c_specific_div")
  }
})

  filtered_data <- reactive(filter_data(example_df, input))
  output$main_table <- renderTable(example_df |> tidyr::unpack("s_race"))
  output$filtered_table <- renderTable(filtered_data())
}

shinyApp(ui, server)

}