【问题标题】:Shiny Reactivity Explaination (using ObserveEvent)闪亮的反应性解释(使用 ObserveEvent)
【发布时间】:2016-06-01 16:57:43
【问题描述】:

我希望使用下面的简化代码作为示例,了解 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")
    )
  )
))

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    如果您将行 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())
    })
    

    【讨论】:

    • 非常感谢。现在很有意义
    猜你喜欢
    • 2019-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-23
    • 2018-05-27
    • 2020-10-13
    • 2020-12-18
    • 2018-05-02
    相关资源
    最近更新 更多