For these exercises we’ll be using the penguins data from the {palmerpenguins} R package. After installing the package, you can load it into R:
library(palmerpenguins)penguins
Examples
This section includes code for the examples shown. These may differ slightly from the examples shown in the live demonstration.
Example 1: Building a basic app structure
See example
app.R
library(shiny)# UI ----------------------------------------------------------------------ui <-fluidPage()# Server ------------------------------------------------------------------server <-function(input, output) {}# Run app -----------------------------------------------------------------shiny::shinyApp(ui, server)
*Other options instead of fluidPage() exist.
Example 2: Developing a user interface
See example
app.R
library(shiny)library(palmerpenguins)# Penguin typesspecies_choices <-unique(penguins$species)# UI ----------------------------------------------------------------------ui <-fluidPage(titlePanel("Penguins!"),sidebarLayout(# Sidebar with user inputssidebarPanel(# Select variable for plotselectInput(inputId ="species",label ="Choose a species:",choices = species_choices ) ),# Display a plot of the generated distributionmainPanel() ))# Server ------------------------------------------------------------------server <-function(input, output) {}# Run app -----------------------------------------------------------------shiny::shinyApp(ui, server)
Example 3: Adding reactive elements
See example
app.R
library(shiny)library(palmerpenguins)# Penguin typesspecies_choices <-unique(penguins$species)# UI ----------------------------------------------------------------------ui <-fluidPage(titlePanel("Penguins!"),sidebarLayout(# Sidebar with user inputssidebarPanel(# Select variable for plotselectInput(inputId ="species",label ="Choose a species:",choices = species_choices ) ),# Display a plot of the generated distributionmainPanel(plotOutput("penguinsPlot") ) ))# Server ------------------------------------------------------------------server <-function(input, output) { filter_data <-reactive({ penguins[penguins$species == input$species, ] }) output$penguinsPlot <-renderPlot({plot(filter_data()$bill_length_mm, filter_data()$bill_depth_mm,main = glue::glue("Bill length and depth of {input$species} penguins")) })}# Run app -----------------------------------------------------------------shiny::shinyApp(ui, server)