กรณีศึกษา: การสร้างเว็บแอปพลิเคชันด้วย Shiny ใน R
Dean Attali
Shiny Consultant
x เปลี่ยน สิ่งที่ขึ้นอยู่กับ x จะถูกประเมินใหม่เปรียบเทียบกับ R แบบปกติ:
x <- 5
y <- x + 1
x <- 10
ค่าของ y คืออะไร? 6 หรือ 11?
input$<inputId> ภายใน render function จะทำให้ output render ใหม่
output$my_plot <- renderPlot({
plot(rnorm( input$num ))
})
output$my_plot ขึ้นอยู่กับ input$num
input$num เปลี่ยน ⇒
output$my_plot จะ react
render*() ทุกตัวคือ reactive contextserver <- function(input, output) {
print(input$num)
}
ERROR: Operation not allowed without an active reactive context.
ใช้ observe({ ... }) เพื่อเข้าถึงตัวแปร reactive
server <- function(input, output) {
observe({
print( input$num )
})
}
มีประโยชน์สำหรับการ debug และติดตามตัวแปร reactive
observe({
print( input$num1 )
print( input$num2 )
})
ใช้ reactive({ ... }) เพื่อสร้างตัวแปร reactive
ผิด:
server <- function(input, output) {
x <- input$num + 1
}
ERROR: Operation not allowed without an active reactive context.
ถูก:
server <- function(input, output) {
x <- reactive({
input$num + 1
})
}
()server <- function(input, output){
x <- reactive({
input$num + 1
})
observe({
print( input$num )
print( x() )
})
}
กรณีศึกษา: การสร้างเว็บแอปพลิเคชันด้วย Shiny ใน R