Reactive वैरिएबल्स से कोड डुप्लिकेशन कम होता है
पिछले अभ्यासों में, इनपुट वैल्यूज़ के अनुसार gapminder को फ़िल्टर करने वाला कोड तीन बार डुप्लिकेट हुआ है: एक बार टेबल में, एक बार प्लॉट में, और एक बार डाउनलोड हैंडलर में.
Reactive वैरिएबल्स का उपयोग करके कोड डुप्लिकेशन कम किया जा सकता है. यह आम तौर पर अच्छा होता है, क्योंकि इससे मेंटेनेंस आसान हो जाता है.
यह अभ्यास पाठ्यक्रम का हिस्सा है
केस स्टडीज़: R में Shiny के साथ वेब एप्लिकेशन बनाना
अभ्यास निर्देश
डेटा को फ़िल्टर करने वाले डुप्लिकेटेड कोड चंक्स हटा दिए गए हैं. आपका काम है एक रिएक्टिव वैरिएबल जोड़ना जो डेटा फ़िल्टर करे, और फिर उसी वैरिएबल का उपयोग करना. विशेष रूप से:
reactive()फंक्शन का उपयोग करकेfiltered_dataनाम का एक रिएक्टिव वैरिएबल बनाएँ, जो पिछले अभ्यास के फ़िल्टरिंग कोड का उपयोग करे (लाइन 15).- इस रिएक्टिव वैरिएबल का उपयोग करके टेबल आउटपुट, प्लॉट आउटपुट, और डाउनलोड फ़ाइल रेंडर करें (लाइन्स 33, 42, और 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))),
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)