LoslegenKostenlos loslegen

Allow "All" continents to be viewed

Before adding the continent selector, the Shiny app showed data for all continents. Now that the continent selector was added, the data can be viewed per continent. But what if the user decides they actually don't want to filter for a specific continent, and they prefer to see all of them? Unfortunately, adding the continent selector removed that ability.

The choices argument of the selectInput() function can be modified to add another value to the continent list, and when this value is chosen, continent filtering can be turned off.

Diese Übung ist Teil des Kurses

Case Studies: Building Web Applications with Shiny in R

Kurs anzeigen

Anleitung zur Übung

Add an option in the select input to select "All" continents. When that option is selected, do not perform any continent filtering. Specifically:

  • Add an "All" value to the list of options that are provided to the select input in the UI.
  • In the server, use an if statement to check if the continent is set to "All". If "All" is chosen, then do not perform any filtering on continents (line 20).

Interaktive Übung

Versuche dich an dieser Übung, indem du diesen Beispielcode vervollständigst.

ui <- fluidPage(
  h1("Gapminder"),
  sliderInput(inputId = "life", label = "Life expectancy",
              min = 0, max = 120,
              value = c(30, 50)),
  # Add an "All" value to the continent list
  selectInput("continent", "Continent",
              choices = c(___, levels(gapminder$continent))),
  tableOutput("table")
)

server <- function(input, output) {
  output$table <- renderTable({
    data <- gapminder
    data <- subset(
      data,
      lifeExp >= input$life[1] & lifeExp <= input$life[2]
    )
    # Don't subset the data if "All" continent are chosen
    if (___) {
      data <- subset(
        data,
        continent == input$continent
      )
    }
    data
  })
}

shinyApp(ui, server)
Code bearbeiten und ausführen