Reactivity 101

กรณีศึกษา: การสร้างเว็บแอปพลิเคชันด้วย Shiny ใน R

Dean Attali

Shiny Consultant

พื้นฐาน Reactivity

  • Shiny ใช้ reactive programming
  • Output จะ react ต่อการเปลี่ยนแปลงของ input
  • เมื่อค่าของตัวแปร x เปลี่ยน สิ่งที่ขึ้นอยู่กับ x จะถูกประเมินใหม่
  • เปรียบเทียบกับ R แบบปกติ:

    x <- 5
    y <- x + 1
    x <- 10
    
  • ค่าของ y คืออะไร? 6 หรือ 11?

กรณีศึกษา: การสร้างเว็บแอปพลิเคชันด้วย Shiny ใน R

ตัวแปร Reactive

  • Input ทุกตัวเป็น reactive
  • 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

กรณีศึกษา: การสร้างเว็บแอปพลิเคชันด้วย Shiny ใน R

Reactive Context

  • Reactive value ใช้ได้เฉพาะใน reactive context เท่านั้น
  • ฟังก์ชัน render*() ทุกตัวคือ reactive context
  • การเข้าถึง reactive value นอก reactive context ⇒ เกิด error
server <- function(input, output) { 
    print(input$num)
}
ERROR: Operation not allowed without an active reactive context.
กรณีศึกษา: การสร้างเว็บแอปพลิเคชันด้วย Shiny ใน R

การ Observe ตัวแปร Reactive

  • ใช้ observe({ ... }) เพื่อเข้าถึงตัวแปร reactive

    server <- function(input, output) { 
        observe({ 
            print( input$num )  
        }) 
    }
    
  • มีประโยชน์สำหรับการ debug และติดตามตัวแปร reactive

  • ตัวแปร reactive แต่ละตัวสร้าง dependency
observe({ 
    print( input$num1 ) 
    print( input$num2 )
})
กรณีศึกษา: การสร้างเว็บแอปพลิเคชันด้วย Shiny ใน R

การสร้างตัวแปร Reactive

  • ใช้ 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 
      })
    }
    
กรณีศึกษา: การสร้างเว็บแอปพลิเคชันด้วย Shiny ใน R

ตัวแปร Reactive

  • เรียกใช้ตัวแปร reactive ที่สร้างเองเหมือนฟังก์ชัน:
    • เพิ่มวงเล็บ ()
server <- function(input, output){
    x <- reactive({
        input$num + 1
    }) 
    observe({ 
        print( input$num )
        print( x() ) 
    })
}
กรณีศึกษา: การสร้างเว็บแอปพลิเคชันด้วย Shiny ใน R

มาฝึกกันเถอะ!

กรณีศึกษา: การสร้างเว็บแอปพลิเคชันด้วย Shiny ใน R

Preparing Video For Download...