简体   繁体   English

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

[英]Shiny Reactivity Explaination (using ObserveEvent)

I am hoping to get some clarity on Shiny's reactivity behavior using the simplified code below as example. 我希望使用下面的简化代码作为示例来清楚Shiny的反应行为。

When y is updated in the app, the graph updates. 当y在应用程序中更新时,图表会更新。
When x is updated in the app, the graph does NOT update. 当x在应用程序中更新时,图表不会更新。

I have read Shiny's tutorials and my understanding is that given that I have wrapped both test() and plot() functions in observeEvent, both parameters should not cause the graph to update when changed. 我已经阅读了Shiny的教程,我的理解是,鉴于我在observeEvent中包含了test()和plot()函数,这两个参数都不应该导致图形在更改时更新。

Can someone help explain the logic behind this? 有人可以帮助解释这背后的逻辑吗?

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")
    )
  )
))

If you put the line x = test(input$x) inside of the renderPlot it will react when either x or y changes. 如果将行x = test(input$x)放在renderPlot ,它将在x或y更改时作出反应。 Essentially the observer creates a reactive output when the action button is clicked the first time, then you simply have a reactive element that responds to changes to inputs inside of it. 实际上,观察者在第一次单击操作按钮时会创建一个反应输出,然后您只需要一个响应元素来响应其内部输入的更改。 Hope that helps. 希望有所帮助。

To make it so the graph only updates when the button is clicked, you will probably need to put the data that is being graphed in a eventReactive and use that as the input for the graph. 为了使图形仅在单击按钮时更新,您可能需要将正在绘制的数据放在eventReactive中并将其用作图形的输入。

Something like this: 像这样的东西:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM