Завантажте відфільтровані дані
Завантаження файлів здійснюється парою функцій downloadButton() і downloadHandler(). Ці дві функції працюють у парі подібно до того, як поєднуються функції output і render: downloadButton() визначає, де в UI з'явиться кнопка, а downloadHandler() потрібно зберегти до списку output, і саме він містить R‑код для створення завантажуваного файлу.
Ця вправа є частиною курсу
Case Studies: створення вебзастосунків із Shiny в R
Інструкції до вправи
Додайте можливість завантажувати дані, які зараз відображено в таблиці, як файл CSV. Зокрема:
- Додайте до UI кнопку завантаження з ID "download_data" і міткою "Download".
- Додайте до сервера download handler (рядок 31).
- Задайте завантажуваному файлу ім'я "gapminder_data.csv" (рядок 33).
- Запишіть відфільтровані дані у файл CSV (рядок 50).
Інтерактивна практична вправа
Спробуйте виконати цю вправу, доповнивши цей зразок коду.
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)