Get startedGet started for free

Add a year filter: numeric slider input

Slider inputs can be used for similar purposes to numeric inputs, as they both provide the user with a way to select a number.

If the initial provided value (the value argument) of the slider is a single number, then the slider will be used to select single numbers. However, if the initial value is a vector of two numbers, then the slider will be used to select two numbers instead of just a single value.

We have already seen that different inputs may have different arguments. It can be difficult to remember the exact arguments each input uses. The only way to find out what arguments you can use with a specific input function is by looking at its documentation or help file.

This exercise is part of the course

Case Studies: Building Web Applications with Shiny in R

View Course

Exercise instructions

  • Add a sliderInput() to the UI with ID "years" and a label of "Years" (line 14).
    • Set the minimum value to the earliest year in the dataset, and the maximum value to the latest year in the dataset.
    • By default, the endpoints of the slider should be set to 1977 and 2002, so that only data between these two years (inclusive) is shown.
  • Add code to the server such that the years that are chosen in the input are used to subset the gapminder data, and only records within these years will show up (line 28).

Hands-on interactive exercise

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

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      textInput("title", "Title", "GDP vs life exp"),
      numericInput("size", "Point size", 1, 1),
      checkboxInput("fit", "Add line of best fit", FALSE),
      radioButtons("color", "Point color",
                   choices = c("blue", "red", "green", "black")),
      selectInput("continents", "Continents",
                  choices = levels(gapminder$continent),
                  multiple = TRUE,
                  selected = "Europe"),
      # Add a slider selector for years to filter
      ___("years", ___, ___, ___, ___)
    ),
    mainPanel(
      plotOutput("plot")
    )
  )
)

# Define the server logic
server <- function(input, output) {
  output$plot <- renderPlot({
    # Subset the gapminder data by the chosen years
    data <- subset(gapminder,
                   continent %in% input$continents &
                   year >= ___$years[1] & year <= ___$years[2])
    
    p <- ggplot(data, aes(gdpPercap, lifeExp)) +
      geom_point(size = input$size, col = input$color) +
      scale_x_log10() +
      ggtitle(input$title)
    
    if (input$fit) {
      p <- p + geom_smooth(method = "lm")
    }
    p
  })
}

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