Filtering in Shiny apps

Author

Derek Sollberger

Published

August 31, 2024

For my data science lectures, I want to be able to run small Shiny apps (e.g. to demonstrate dplyr concepts). With my current knowledge of Shiny code, I am rather sure that I will need a reactive data frame to carry out the following demonstration:

Using data from the USDA NASS, plot a time series of bee colony population counts, but allow the user to filter the results by each of the United States regions.

library("shiny")
library("tidyverse")

bee_df <- readr::read_csv("bee_population_states.csv")
US_states <- unique(bee_df$State)
#| echo: false
#| standalone: true
#| viewerHeight: 800
ui <- fluidPage(
  titlePanel("Bee Populations"),
  sidebarLayout(
    sidebarPanel(
      selectInput("chosen_state", "Select location", 
                  choices = US_states,
                  selected = "OTHER STATES")
    ),
    mainPanel(
      plotOutput(outputId = "beePlot")
    )
  )
)
server <- function(input, output) {
  filtered_data <- reactive({
    bee_df %>%
      filter(State == input$chosen_state)
  })
  
  output$beePlot <- renderPlot({
    filtered_data() %>%
      ggplot(aes(x = Year, y = Value)) +
      geom_bar(stat = "identity")
  })
}
shinyApp(ui = ui, server = server)