Reactive contexts
Reactive values เป็น construct พิเศษใน Shiny ที่ไม่พบในโค้ด R ทั่วไป จึงไม่สามารถใช้งานในโค้ด R ใด ๆ ได้ตามอำเภอใจ — Reactive values จะเข้าถึงได้ภายใน reactive context เท่านั้น
นี่คือเหตุผลที่ตัวแปรซึ่งขึ้นอยู่กับ reactive value ต้อง สร้างด้วยฟังก์ชัน reactive() มิฉะนั้นจะเกิดข้อผิดพลาด ตัว Shiny server เองไม่ใช่ reactive context แต่ฟังก์ชัน reactive(), ฟังก์ชัน observe() และฟังก์ชัน render*() ทุกตัวเป็น reactive context
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
กรณีศึกษา: การสร้างเว็บแอปพลิเคชันด้วย Shiny ใน R
คำแนะนำการฝึกหัด
แอป Shiny ที่ให้มามี numeric input สองตัวคือ num1 และ num2 พร้อมด้วย text output โดยมีสิ่งที่ต้องทำดังนี้
- สร้างตัวแปร reactive ชื่อ
my_sumเพื่อคำนวณผลรวมของ numeric input ทั้งสองตัว (บรรทัดที่ 10) - สร้างตัวแปร reactive ชื่อ
my_averageเพื่อคำนวณค่าเฉลี่ยของ input ทั้งสองตัว (บรรทัดที่ 14) - แสดงค่าเฉลี่ยที่คำนวณได้ใน text output โดยใช้ตัวแปร reactive (บรรทัดที่ 23)
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
ui <- fluidPage(
numericInput("num1", "Number 1", 5),
numericInput("num2", "Number 2", 10),
textOutput("result")
)
server <- function(input, output) {
# Calculate the sum of the inputs
my_sum <- reactive({
input$num1 + ___
})
# Calculate the average of the inputs
my_average <- ___({
my_sum() / 2
})
output$result <- renderText({
paste(
# Print the calculated sum
"The sum is", my_sum(),
# Print the calculated average
"and the average is", ___
)
})
}
shinyApp(ui, server)