# Shiny app demo - UW Data Science Working Group # March 23, 2022 # Notes about Shiny- # (1) Keep track of parentheses and commas! They are the #1 issue I encounter when it comes to error messages. # (2) Make sure all of your ID names are unique, otherwise Shiny will get confused when calling them between the user interface and the server. #### Setup #### # Load packages library(tidyverse) library(shiny) library(shinythemes) library(palmerpenguins) # Load data dat <- penguins # Any additional data should be loaded in here. #### User interface #### ui <- fluidPage( theme = shinytheme("superhero"), # changes app theme titlePanel("Penguin Shiny App"), # title sidebarLayout( # creates the layout sidebarPanel("Widgets go here.", # sidebar title # our first widget - dropdown menu selectInput(inputId = "island_select", # variable name label = "Select an island.", # user instructions choices = unique(dat$island) # choices displayed ), # our second widget - multiple choice radioButtons(inputId = "species_select", label = "Select a species.", choices = unique(dat$species)) ), mainPanel("Outputs go here.", # main panel title # our first output - penguin plot p("Penguin Plot:"), # the p() command creates a new paragraph plotOutput(outputId = "penguin_plot"), # our second output - penguin table p("Penguin Bill Summary Statistics:"), tableOutput(outputId = "penguin_table") ) ) ) #### Server #### server <- function(input, output) { # create a new dataset based on selected island penguin_island <- reactive({ # reactive tells shiny to monitor user's selections dat %>% filter(island == input$island_select) }) # create a plot output$penguin_plot <- renderPlot({ # render tells shiny to monitor changes ggplot(penguin_island(), # parentheses indicate the dataset is not static aes(x = species, y = body_mass_g)) + geom_boxplot(aes(fill = sex)) + labs(x = "Species", y = "Body Mass (g)", fill = "Sex") + theme_minimal() }) # create another new dataset penguin_species <- reactive({ dat %>% filter(species == input$species_select) %>% group_by(sex) %>% summarize(Length = mean(bill_length_mm, na.rm = TRUE), Depth = mean(bill_depth_mm, na.rm = TRUE)) }) # create a table output$penguin_table <- renderTable({ penguin_species() }) } #### Combine the user interface and server #### shinyApp(ui = ui, server = server)