Reaktive Variablen verringern Code-Duplizierung
In den vorherigen Übungen wurde der Code zum Filtern von gapminder entsprechend den Eingabewerten dreimal dupliziert: einmal in der Tabelle, einmal im Plot und einmal im Download-Handler.
Reaktive Variablen können verwendet werden, um Code-Duplizierung zu reduzieren. Das ist grundsätzlich eine gute Idee, weil es die Wartung erleichtert.
Diese Übung ist Teil des Kurses
Fallstudien: Webanwendungen mit Shiny in R erstellen
Anleitung zur Übung
Die duplizierten Code-Blöcke, die die Daten filtern, wurden entfernt. Deine Aufgabe ist es, eine reaktive Variable hinzuzufügen, die die Daten filtert, und stattdessen diese Variable zu verwenden. Konkret:
- Erstelle eine reaktive Variable namens
filtered_datamit der Funktionreactive(), die den Filtercode aus der vorherigen Übung verwendet (Zeile 15). - Nutze die reaktive Variable, um die Tabellen-Ausgabe, die Plot-Ausgabe und die Download-Datei zu erzeugen (Zeilen 33, 42 und 50).
Interaktive Übung
Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.
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)