Filter by life expectancy
The real benefit of using Shiny comes when inputs are combined with outputs. The table created in the last exercise is static—it cannot be changed—but for exploration, it would be better if the user could decide what subset of the data to see.
This can be achieved by adding an input that lets the user select a value to filter the data. This way, the table we created in the previous exercise can be made dynamic.
One of the variables in the gapminder
dataset is lifeExp
(life expectancy). Your task is to add a slider input to the Shiny app that lets the user choose a minimum and maximum life expectancy, and the table will only show data that matches these values.
This exercise is part of the course
Case Studies: Building Web Applications with Shiny in R
Exercise instructions
- Add a slider input to the UI with ID "life", a minimum value of 0, maximum value of 120, and default selection of 30-50.
- Inside the render function, use the input value to subset the
gapminder
data to only include records with alifeExp
that is between the minimum and maximum values (both inclusive).
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
ui <- fluidPage(
h1("Gapminder"),
# Add a slider for life expectancy filter
___(inputId = ___, label = "Life expectancy",
min = ___, max = ___,
value = c(30, 50)),
tableOutput("table")
)
server <- function(input, output) {
output$table <- renderTable({
data <- gapminder
data <- subset(
data,
# Use the life expectancy input to filter the data
lifeExp >= ___life[1] & lifeExp <= ___life[2]
)
data
})
}
shinyApp(ui, server)