闪亮反应性解释(使用 ObserveEvent)

hjw*_*hjw 4 r shiny

我希望使用下面的简化代码作为示例,清楚地了解 Shiny 的反应行为。

当 y 在应用程序中更新时,图表也会更新。
当 x 在应用程序中更新时,图表不会更新。

我已经阅读了 Shiny 的教程,我的理解是,鉴于我已将 test() 和plot() 函数包装在observeEvent 中,这两个参数不应导致图表在更改时更新。

有人可以帮忙解释一下这背后的逻辑吗?

library(shiny)

test <- function(x){x*2}

shinyServer(function(input, output, session) {

  observeEvent(input$run, {
    x = test(input$x)
    output$distPlot <- renderPlot({
      if(input$y){
        x = x+2
      }
      plot(x)
    })
  })

})

shinyUI(fluidPage(

  sidebarLayout(
      sidebarPanel(
      numericInput("x", "x:", 10),
      checkboxInput("y", label = "y", value = FALSE),
      actionButton("run", "run")
    ),

    mainPanel(
      plotOutput("distPlot")
    )
  )
))
Run Code Online (Sandbox Code Playgroud)

Car*_*arl 5

如果你把线放在x = test(input$x)里面,renderPlot当 x 或 y 改变时它就会做出反应。本质上,当第一次单击操作按钮时,观察者会创建一个反应性输出,然后您只需拥有一个反应性元素来响应其内部输入的更改。希望有帮助。

为了使图表仅在单击按钮时更新,您可能需要将绘制图表的数据放入 eventReactive 中,并将其用作图表的输入。

像这样的东西:

data <- eventReactive(input$run, {
    x = test(input$x)
    if(input$y){
      x = x+2
    }
    x
  })
output$distPlot <- renderPlot({
  plot(data())
})
Run Code Online (Sandbox Code Playgroud)