案例研究:使用 R 的 Shiny 建置網頁應用程式
Dean Attali
Shiny Consultant
x 的值改變,所有依賴 x 的內容都會重新計算與一般 R 相比:
x <- 5
y <- x + 1
x <- 10
y 的值是幾?6 還是 11?
在 render 函式內使用 input$<inputId> 會使輸出重新渲染
output$my_plot <- renderPlot({
plot(rnorm( input$num ))
})
output$my_plot 依賴 input$num
input$num 改變 ⇒
output$my_plot 會反應
render*() 函式都是 reactive 環境server <- 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 )
})
}
適合偵錯,用來追蹤 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() )
})
}
案例研究:使用 R 的 Shiny 建置網頁應用程式