Get startedGet started for free

Your first shinyApp

You have seen how inputs and outputs can be put together in a shinyApp. You have also seen how a shinyApp can be constructed to communicate results from the sleep study.

Your goal now is to create a shinyApp to report two main results:

  1. The distribution of sleep hours
  2. The median sleep hours amongst different age groups

In this exercise, we have stored the data in the form of a dplyr data frame called sleep, and the shiny and tidyverse libraries have already been loaded.

Now it's your turn to create your own shinyApp!

This exercise is part of the course

Building Dashboards with shinydashboard

View Course

Exercise instructions

  • Add two plot outputs called "histogram" and "barchart" to the mainPanel.
  • In the choiceNames argument in checkboxGroupInput(), replace its contents with icons called "calendar", "briefcase" and "gift".
  • Define the two outputs, one called histogram, and another called barchart.
  • Use the shinyApp() function to render the shiny app.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

ui <- fluidPage(
  titlePanel("Sleeping habits in America"), 
  fluidRow(
  # Place two plots here, called "histogram" and "barchart"
  mainPanel(___("histogram"), ___("barchart")), 
  inputPanel(sliderInput("binwidth", 
                         label = "Bin width", 
                         min = 0.1, max = 2, 
                         step = 0.01, value=0.25),
             checkboxGroupInput("days", "Choose types of days:",
                                # Replace the list elements with icons called "calendar", "briefcase" and "gift"
                                choiceNames = list("All days", 
                                                   "Non-holiday weekdays", 
                                                   "Weekend days/holidays"), 
                                choiceValues = list("All days", 
                                                    "Nonholiday weekdays", 
                                                    "Weekend days and holidays"))), 
  "In general, across the different age groups, Americans seem to get adequate daily rest." ))

server <- function(input, output, session) {
  # Define the histogram and barchart
  output$histogram <- ___({
    ggplot(sleep, aes(x=`Avg hrs per day sleeping`)) + 
    geom_histogram(binwidth = input$binwidth, col='white') + 
    theme_classic()
  })
  ___ <- ___({
    filter(sleep, `Type of Days` %in% input$days) %>%
      group_by(`Type of Days`, `Age Group`) %>%
      summarize(`Median hours` = median(`Avg hrs per day sleeping`)) %>%
      ggplot(aes(x = `Median hours`, y = `Age Group`, fill = `Type of Days`)) +
      geom_col(position = 'dodge') + theme_classic()
  })
}

# Use shinyApp() to render the shinyApp
___
Edit and Run Code