फ़िल्टर किया हुआ डेटा डाउनलोड करें
फाइलें डाउनलोड करना downloadButton() और downloadHandler() फंक्शनों की जोड़ी से किया जाता है. ये दोनों फंक्शन वैसे ही साथ काम करते हैं जैसे आउटपुट और रेंडर फंक्शन की जोड़ियाँ: downloadButton() तय करता है कि UI में यह कहाँ दिखेगा, जबकि downloadHandler() को output लिस्ट में सेव करना होता है और इसमें डाउनलोड की जाने वाली फाइल बनाने का वास्तविक R कोड होता है.
यह अभ्यास पाठ्यक्रम का हिस्सा है
केस स्टडीज़: R में Shiny के साथ वेब एप्लिकेशन बनाना
अभ्यास निर्देश
टेबल में जो डेटा आप अभी देख रहे हैं, उसे CSV फाइल के रूप में डाउनलोड करने की सुविधा जोड़ें. खास तौर पर:
- UI में ID "download_data" और लेबल "Download" वाला एक डाउनलोड बटन जोड़ें.
- सर्वर में एक डाउनलोड हैंडलर जोड़ें (लाइन 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)