Shiny Exercise 4

Create and Use Input

Published

May 5, 2025

Goal: Enable filtering by storm status.

# R packages
library(shiny)
library(dplyr)
theme_set(theme_minimal())

# data preps
data(storms)

stormNames <- storms |>
  select(name, year, status) |>
  distinct() |>
  group_by(name, status) |>
  summarize(count = n()) |>
  arrange(desc(count))

unique(stormNames$status)

# ui
ui <- fluidPage(
  
  "The plot below shows the distribution of storm name use.",
  
  # 1. nameDist
  plotOutput("nameDist")
)

server <- function(input, output, session) {
  
  # 1. nameDist
  output$nameDist <- renderPlot({
    
    ggplot(data = stormNames) +
      geom_histogram(aes(x = count)) 
    
  })
  
}

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

# data preps
data(storms)

stormNames <- storms |>
  select(name, year, status) |>
  distinct() |>
  group_by(name, status) |>
  summarize(count = n()) |>
  arrange(desc(count))


# ui
ui <- fluidPage(
  
  # 1. stormStatus
  selectInput("stormStatus",
              label = "Filter by storm type: ",
              choices = unique(stormNames$status)),
  
  "The plot below shows the distribution of storm name use.",
  
  # 2. nameDist
  plotOutput("nameDist")
)

server <- function(input, output, session) {
  
  # 2. nameDist
  output$nameDist <- renderPlot({
    
    str(input$stormStatus)  # 1. stormStatus
    
    ggplot(data = 
             stormNames |> 
             filter(status == input$stormStatus)) +   # 1. stormStatus
      geom_histogram(aes(x = count), 
                     bins = 5) + 
      xlab(input$stormStatus)   # 1. stormStatus
  },
  
  width = 400, height = 300)
  
}

shinyApp(ui, server)
Back to top