案例研究:使用 R 的 Shiny 构建 Web 应用
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*() 函数都是响应式上下文server <- function(input, output) {
print(input$num)
}
ERROR: Operation not allowed without an active reactive context.
使用 observe({ ... }) 访问响应式变量
server <- function(input, output) {
observe({
print( input$num )
})
}
便于调试,跟踪响应式变量
observe({
print( input$num1 )
print( input$num2 )
})
使用 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 构建 Web 应用