微调反应性

案例研究:使用 R 的 Shiny 构建 Web 应用

Dean Attali

Shiny Consultant

反应性回顾

  • reactive() 和 input$ 是反应式
  • 依赖反应式变量的代码会在依赖更新时重跑
  • 读取反应式值会将其设为依赖
x <- reactive({
    y() * input$num1 * input$num2
})
案例研究:使用 R 的 Shiny 构建 Web 应用

isolate

  • 用 isolate() 避免创建反应式依赖
  • 若在 isolate() 中的反应式值被修改,不会触发任何变化
x <- reactive({
    y() * isolate({ input$num1 }) * input$num2
})
x <- reactive({
    y() * isolate({ input$num1 * input$num2 })
})
案例研究:使用 R 的 Shiny 构建 Web 应用

全部隔离

  • 有时需要隔离所有反应式

    x <- reactive({
        isolate({
            y() * input$num1 * input$num2
        })
    })
    
  • 需要一种按需触发 x 重跑的方法

案例研究:使用 R 的 Shiny 构建 Web 应用

操作按钮(Action buttons)

actionButton(inputId, label, ...)

chapter4_4_fine_tune_the_activity.025.png

  • 仅一种简单交互:点击
  • 按钮的值为点击次数
# 点击按钮两次后
str(input$button)
int 2
案例研究:使用 R 的 Shiny 构建 Web 应用

用操作按钮触发反应性

  • 在 server 中读取按钮输入会触发反应性

  • 在 UI 中添加按钮

    actionButton(inputId = "calculate_x", label = "Calculate x!")
    
  • 访问按钮以建立依赖

    x <- reactive({
        input$calculate_x
    
        isolate({
            y() * input$num1 * input$num2
        })
    })
    
案例研究:使用 R 的 Shiny 构建 Web 应用

Passons à la pratique !

案例研究:使用 R 的 Shiny 构建 Web 应用

Preparing Video For Download...