Reactive variables reduce code duplication
In the previous exercises, the code to filter gapminder
according to the input values is duplicated three times: once in the table, once in the plot, and once in the download handler.
Reactive variables can be used to reduce code duplication, which is generally a good idea because it makes maintenance easier.
Cet exercice fait partie du cours
Case Studies: Building Web Applications with Shiny in R
Instructions
The duplicated code chunks that filter the data have been removed. Your task is to add a reactive variable that filters the data, and use this variable instead. Specifically:
- Create a reactive variable named
filtered_data
by using thereactive()
function that uses the filtering code from the previous exercise (line 15). - Use the reactive variable to render the table output, the plot output, and the download file (lines 33, 42, and 50).
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
ui <- fluidPage(
h1("Gapminder"),
sliderInput(inputId = "life", label = "Life expectancy",
min = 0, max = 120,
value = c(30, 50)),
selectInput("continent", "Continent",
choices = c("All", levels(gapminder$continent))),
downloadButton(outputId = "download_data", label = "Download"),
plotOutput("plot"),
tableOutput("table")
)
server <- function(input, output) {
# Create a reactive variable named "filtered_data"
filtered_data <- ___({
# Filter the data (copied from previous exercise)
data <- gapminder
data <- subset(
data,
lifeExp >= input$life[1] & lifeExp <= input$life[2]
)
if (input$continent != "All") {
data <- subset(
data,
continent == input$continent
)
}
data
})
output$table <- renderTable({
# Use the filtered_data variable to render the table output
data <- ___
data
})
output$download_data <- downloadHandler(
filename = "gapminder_data.csv",
content = function(file) {
# Use the filtered_data variable to create the data for
# the downloaded file
data <- ___
write.csv(data, file, row.names = FALSE)
}
)
output$plot <- renderPlot({
# Use the filtered_data variable to create the data for
# the plot
data <- ___
ggplot(data, aes(gdpPercap, lifeExp)) +
geom_point() +
scale_x_log10()
})
}
shinyApp(ui, server)