Shiny Exercise 5

Display Storms for a User-Selected Year

Published

May 5, 2025

Goal: Enable User Input to Select a Year

  1. Add a sliderInput() element to the ui.
  2. Modify the renderTable({}) expression to filter the year displayed to the one selected by the user.
# R packages
library(shiny)
library(tidyverse)

# data preps
data(storms)
storms_by_year <- storms |>
  group_by(year) |>
  summarize(n = n_distinct(name))


# ui
ui <- fluidPage(
  
## add code to create sliderInput here to filter by year.
## see ?sliderInput
  
  # 1. yr
  sliderInput("yr",
              label = "Filter by year: ",
              value = 2000,
              min = min(storms_by_year$year),
              max = max(storms_by_year$year)
              ),
  
  # 2. byYearTable
  tableOutput("byYearTable")
  
  )

server <- function(input, output, session) {
  
  # 2. byYearTable
  output$byYearTable <- renderTable({
    storms_by_year |> 
      filter(year == input$yr ) # 1. yr
  })
  
}

shinyApp(ui, server)
Click to Check the Complete Shiny App Code!
# R packages
library(shiny)
library(dplyr)

# data preps
data(storms)
storms_by_year <- storms |>
  group_by(year) |>
  summarize(n = n_distinct(name))


# ui
ui <- fluidPage(
  
  ## add code to create sliderInput to select a year.
  ## see ?sliderInput
  
  # 1. year
  sliderInput("year", 
              "Select year to display",
              value = 1990,
              min = min(storms_by_year$year),
              max = max(storms_by_year$year), 
              step = 1,
              sep = ""),
  
  # 2. byYearTable
  tableOutput("byYearTable")
  
  )

server <- function(input, output, session) {
  
  # 2. byYearTable
  output$byYearTable <- renderTable({
    
    str(input$year)  # 1. year
    
    storms_by_year |> 
      filter(year == input$year)  # 1. year
    
  },
  digits = 0)
  
}

shinyApp(ui, server)
Back to top