Tải xuống dữ liệu đã lọc
Việc tải xuống tệp được thực hiện bằng cặp hàm downloadButton() và downloadHandler(). Hai hàm này kết hợp với nhau tương tự như cách cặp hàm output và render hoạt động: downloadButton() quyết định vị trí hiển thị trong UI, còn downloadHandler() cần được lưu vào danh sách output và chứa mã R thực tế để tạo tệp được tải xuống.
Bài tập này là một phần của khóa học
Nghiên cứu tình huống: Xây dựng ứng dụng web với Shiny trong R
Hướng dẫn bài tập
Thêm khả năng tải xuống dữ liệu hiện đang xem trong bảng dưới dạng tệp CSV. Cụ thể:
- Thêm một nút tải xuống vào UI với ID "download_data" và nhãn "Download".
- Thêm một download handler vào server (dòng 31).
- Đặt tên tệp tải xuống là "gapminder_data.csv" (dòng 33).
- Ghi dữ liệu đã lọc vào một tệp CSV (dòng 50).
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
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)