Get startedGet started for free

Add a slider input to select year

Slider inputs are great for numeric inputs, both when you'd like users to choose from a range of values and also when they should choose a static value from a set of options, but you want to be more creative than using a selectInput().

Adjust your app displaying top 10 names for a year by adding a slider to select a specific year available in babynames.

This exercise is part of the course

Building Web Applications with Shiny in R

View Course

Exercise instructions

  • Add a slider input named "year" to let users select a year between 1900 and 2010, with a default of 1900.
  • Update server code to get the top 10 names for the selected year instead of 1900 only

Hands-on interactive exercise

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

ui <- fluidPage(
  titlePanel("What's in a Name?"),
  # Add select input named "sex" to choose between "M" and "F"
  selectInput('sex', 'Select Sex', choices = c("F", "M")),
  # CODE BELOW: Add slider input named 'year' to select years  (1900 - 2010)

  # Add plot output to display top 10 most popular names
  plotOutput('plot_top_10_names')
)

server <- function(input, output, session){
  # Render plot of top 10 most popular names
  output$plot_top_10_names <- renderPlot({
    # Get top 10 names by sex and year
    top_10_names <- babynames %>% 
      filter(sex == input$sex) %>% 
    # MODIFY CODE BELOW: Filter for the selected year
      filter(year == 1900) %>% 
      slice_max(prop, n = 10)
    # Plot top 10 names by sex and year
      ggplot(top_10_names, aes(x = name, y = prop)) +
        geom_col(fill = "#263e63")
  })
}

shinyApp(ui = ui, server = server)
Edit and Run Code