我希望使用下面的简化代码作为示例,对 Shiny 的 react 行为有一些了解。
当 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")
)
)
))
最佳答案
如果你把这条线x = test(input$x)
内部renderPlot
当 x 或 y 发生变化时,它会使用react。本质上,当第一次单击操作按钮时,观察者会创建一个响应式(Reactive)输出,然后您只需一个响应式(Reactive)元素来响应其内部输入的更改。希望有帮助。
为了使图表仅在单击按钮时更新,您可能需要将正在绘制的数据放入 eventReactive 并将其用作图表的输入。
像这样的东西:
data <- eventReactive(input$run, {
x = test(input$x)
if(input$y){
x = x+2
}
x
})
output$distPlot <- renderPlot({
plot(data())
})
关于r - Shiny 的 react 性解释(使用 ObserveEvent),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37574682/