Reactivity 101

案例研究:使用 R 的 Shiny 建置網頁應用程式

Dean Attali

Shiny Consultant

Reactivity 基礎

  • Shiny 採用 reactive programming
  • 輸出會因輸入變動而反應
  • 當變數 x 的值改變,所有依賴 x 的內容都會重新計算
  • 與一般 R 相比:

    x <- 5
    y <- x + 1
    x <- 10
    
  • y 的值是幾?6 還是 11?

案例研究:使用 R 的 Shiny 建置網頁應用程式

Reactive 變數

  • 所有輸入皆為 reactive
  • 在 render 函式內使用 input$<inputId> 會使輸出重新渲染

    output$my_plot <- renderPlot({
        plot(rnorm( input$num ))
    })
    
  • output$my_plot 依賴 input$num

    • input$num 改變 ⇒

      output$my_plot 會反應

案例研究:使用 R 的 Shiny 建置網頁應用程式

Reactive 環境

  • Reactive 值只能在 reactive 環境 中使用
  • 任何 render*() 函式都是 reactive 環境
  • 在 reactive 環境外存取 reactive 值 ⇒ 會出錯
server <- function(input, output) { 
    print(input$num)
}
ERROR: Operation not allowed without an active reactive context.
案例研究:使用 R 的 Shiny 建置網頁應用程式

觀察 reactive 變數

  • observe({ ... }) 存取 reactive 變數

    server <- function(input, output) { 
        observe({ 
            print( input$num )  
        }) 
    }
    
  • 適合偵錯,用來追蹤 reactive 變數

  • 每個 reactive 變數都會建立相依性
observe({ 
    print( input$num1 ) 
    print( input$num2 )
})
案例研究:使用 R 的 Shiny 建置網頁應用程式

建立 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 
      })
    }
    
案例研究:使用 R 的 Shiny 建置網頁應用程式

Reactive 變數

  • 存取自訂 reactive 變數時像呼叫函式:
    • 加上括號 ()
server <- function(input, output){
    x <- reactive({
        input$num + 1
    }) 
    observe({ 
        print( input$num )
        print( x() ) 
    })
}
案例研究:使用 R 的 Shiny 建置網頁應用程式

一起來練習吧!

案例研究:使用 R 的 Shiny 建置網頁應用程式

Preparing Video For Download...