ตัวแปร reactive ช่วยลดการเขียนโค้ดซ้ำ
ในแบบฝึกหัดก่อนหน้า โค้ดสำหรับกรองข้อมูล gapminder ตามค่า input ถูกเขียนซ้ำถึงสามครั้ง ได้แก่ ในส่วนของตาราง ในส่วนของกราฟ และในส่วนของ download handler
ตัวแปร Reactive ช่วยลดการเขียนโค้ดซ้ำได้ ซึ่งเป็นแนวปฏิบัติที่ดี เพราะทำให้การดูแลรักษาโค้ดในภายหลังง่ายขึ้น
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
กรณีศึกษา: การสร้างเว็บแอปพลิเคชันด้วย Shiny ใน R
คำแนะนำการฝึกหัด
โค้ดส่วนที่ซ้ำกันสำหรับกรองข้อมูลถูกลบออกแล้ว ให้เพิ่มตัวแปร reactive สำหรับกรองข้อมูล แล้วใช้ตัวแปรนี้แทน โดยมีขั้นตอนดังนี้
- สร้างตัวแปร reactive ชื่อ
filtered_dataโดยใช้ฟังก์ชันreactive()พร้อมใส่โค้ดกรองข้อมูลจากแบบฝึกหัดก่อนหน้า (บรรทัดที่ 15) - นำตัวแปร reactive นี้ไปใช้ในการแสดงผลตาราง กราฟ และไฟล์ดาวน์โหลด (บรรทัดที่ 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)