Gefilterte Daten herunterladen
Dateien lassen sich mit dem Funktionspaar downloadButton() und downloadHandler() herunterladen. Diese beiden Funktionen arbeiten ähnlich zusammen wie Output- und Render-Funktionen: downloadButton() bestimmt, wo im UI die Schaltfläche erscheint, während downloadHandler() in der output-Liste gespeichert wird und den eigentlichen R-Code enthält, um die heruntergeladene Datei zu erzeugen.
Diese Übung ist Teil des Kurses
Fallstudien: Webanwendungen mit Shiny in R erstellen
Anleitung zur Übung
Füge die Möglichkeit hinzu, die aktuell in der Tabelle angezeigten Daten als CSV-Datei herunterzuladen. Konkret:
- Füge im UI eine Download-Schaltfläche mit der ID "download_data" und dem Label "Download" hinzu.
- Füge im Server einen Download-Handler hinzu (Zeile 31).
- Gib der heruntergeladenen Datei den Namen "gapminder_data.csv" (Zeile 33).
- Schreibe die gefilterten Daten in eine CSV-Datei (Zeile 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))),
# Add a download button
___(outputId = ___, label = ___),
plotOutput("plot"),
tableOutput("table")
)
server <- function(input, output) {
output$table <- renderTable({
data <- gapminder
data <- subset(
data,
lifeExp >= input$life[1] & lifeExp <= input$life[2]
)
if (input$continent != "All") {
data <- subset(
data,
continent == input$continent
)
}
data
})
# Create a download handler
output$download_data <- ___(
# The downloaded file is named "gapminder_data.csv"
filename = ___,
content = function(file) {
# The code for filtering the data is copied from the
# renderTable() function
data <- gapminder
data <- subset(
data,
lifeExp >= input$life[1] & lifeExp <= input$life[2]
)
if (input$continent != "All") {
data <- subset(
data,
continent == input$continent
)
}
# Write the filtered data into a CSV file
write.csv(___, file, row.names = FALSE)
}
)
output$plot <- renderPlot({
data <- gapminder
data <- subset(
data,
lifeExp >= input$life[1] & lifeExp <= input$life[2]
)
if (input$continent != "All") {
data <- subset(
data,
continent == input$continent
)
}
ggplot(data, aes(gdpPercap, lifeExp)) +
geom_point() +
scale_x_log10()
})
}
shinyApp(ui, server)