# R packages and setup
library(shiny)
library(DT)
library(plotly)
library(dplyr)
theme_set(theme_minimal())
# data
data(storms)
<- storms |>
storms mutate(time = as.POSIXct(paste(year, month, day, hour, sep = "-"),
format = "%Y-%m-%d-%H"))
<- storms |>
stormsUnique select(name, year) |>
distinct()
# ui
<- fluidPage(
ui
titlePanel("Storm Wind Speed"),
sidebarLayout(
sidebarPanel(
# 1. stormName
selectInput("stormName",
label = "Filter by storm name: ",
choices = unique(stormsUnique$name),
selected = stormsUnique$name[[1]])
),
mainPanel(
p("The plot below shows windspeed for the selected storm."),
# 2. windSpeed
plotOutput("windSpeed")
)
)
)
# server
<- function(input, output, session) {
server
# 2. windSpeed
$windSpeed <- renderPlot({
output
|>
storms filter(name == input$stormName) |> # 1. stormName
select(time, wind) |>
ggplot(aes(x = time, y = wind)) +
geom_point(shape = 1, size = 3) +
geom_line()
})
}
shinyApp(ui, server)
Shiny Exercise 6
HTML widgets DT and Plotly
Goal: Add Client-Side Interactivity using HTML widgets.
Click to Check the Complete Shiny App Code!
# R packages and setup
library(shiny)
library(DT)
library(plotly)
library(dplyr)
theme_set(theme_minimal())
# data preps
data(storms)
<- storms |>
storms mutate(time = as.POSIXct(paste(year, month, day, hour, sep = "-"),
format = "%Y-%m-%d-%H"))
<- storms |>
stormsUnique select(name, year) |>
distinct()
# ui
<- fluidPage(
ui
titlePanel("Storm Wind Speed"),
sidebarLayout(
sidebarPanel(
# 1. nameTable
dataTableOutput("nameTable")
),
mainPanel(
p("The plot below shows windspeed for the selected storm."),
# 2. windSpeed
plotlyOutput("windSpeed")
)
)
)
<- function(input, output, session) {
server
# 1. nameTable
$nameTable <- renderDataTable({
output
stormsUnique
},selection = "single")
# 2. windSpeed
$windSpeed <- renderPlotly({
output
str(reactiveValuesToList(input))
req(input$nameTable_row_last_clicked)
<- slice(stormsUnique,
stormRow as.integer(input$nameTable_row_last_clicked))
<- storms |>
storms_filtered filter(name == stormRow$name &
== stormRow$year) |>
year select(time, wind)
<- ggplot(storms_filtered, aes(x = time, y = wind)) +
p geom_point(shape = 1, size = 3) +
geom_line(color = 'red')
ggplotly(p)
})
}
shinyApp(ui, server)