Examples

Data

{palmerpenguins}

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 types
species_choices <- unique(penguins$species)

# UI ----------------------------------------------------------------------

ui <- fluidPage(
  titlePanel("Penguins!"),
  sidebarLayout(

    # Sidebar with user inputs
    sidebarPanel(
      # Select variable for plot
      selectInput(
        inputId = "species",
        label = "Choose a species:",
        choices = species_choices
      )
    ),

    # Display a plot of the generated distribution
    mainPanel()
  )
)


# 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 types
species_choices <- unique(penguins$species)

# UI ----------------------------------------------------------------------

ui <- fluidPage(
  titlePanel("Penguins!"),
  sidebarLayout(
    
    # Sidebar with user inputs
    sidebarPanel(
      # Select variable for plot
      selectInput(
        inputId = "species",
        label = "Choose a species:",
        choices = species_choices
      )
    ),
    
    # Display a plot of the generated distribution
    mainPanel(
      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)