r - 如何更新 R shiny 中 for 循环内的无功输出

标签 r shiny reactive

我是 Shiny 的新手,遇到了一个我找不到答案的问题。基本上,我有一个 Shiny 的应用程序,它在一个循环中进行一些长时间的计算,我希望它每隔几次迭代就输出一个“进度报告”。然而,即使我在循环中重新分配我的 react 变量,输出也不会更新,直到循环(或整个函数?)完成。

这是我的意思的简化测试用例:

library(shiny)

# Basic interface
ui <- fluidPage(
     actionButton("run", "Run"),
     textOutput("textbox")
)

# Basic server with loop
server <- function(input, output) {

  textvals=reactiveValues(a=0)

  observeEvent(input$run, {
    for(i in 1:10){
      textvals$a=i   # Expect output to update here, but doesn't
      Sys.sleep(0.1) # Slight pause so isn't instantaneous
    }
  })

   output$textbox <- renderText({
      textvals$a
   })
}

# Run the application 
shinyApp(ui = ui, server = server)

我希望显示会在循环执行时更新 1, 2, 3, ... 10。相反,它只是从 0 直接跳到 10。如何在循环的中途强制更新?

谢谢。

最佳答案

通过使用 invalidateLater,您可以获得接近您想要的东西。我认为这不是最短的方法,但它可以帮助您找到更好的解决方案。

library(shiny)

# Basic interface
ui <- fluidPage(
  actionButton("run", "Run"),
  textOutput("textbox")
)

# Basic server with loop
server <- function(input, output, session) {

  textvals <- reactiveVal(0)
  active <- reactiveVal(FALSE)

  output$textbox <- renderText({
   textvals()
  })

  observe({
    invalidateLater(1000, session)
    isolate({
      if (active()) {
        textvals(textvals() + 1)
        if (textvals() > 9) {
          active(FALSE)
        }
      }
    })
  })

  observeEvent(input$run, {
    active(TRUE)
  })
}

# Run the application 
shinyApp(ui = ui, server = server)

顺便说一下,响应式(Reactive)循环和 for 循环并不太顺利。这可能有帮助:https://gist.github.com/bborgesr/e1ce7305f914f9ca762c69509dda632e

关于r - 如何更新 R shiny 中 for 循环内的无功输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58080347/

相关文章:

r - 使用 AWS 与 R 进行并行处理

减少 R 中的列表以匹配另一个列表。

r - Shiny 中的 conditionalPanel 不起作用

r - R Shiny 中的图像幻灯片

java - 用 Mono 压缩 Flux 的正确方法是什么?

r - 使用 selectInput 从 R Shiny 中的数据下载多个变量时出现问题

r - 带垂直线的散点图 - Lollipop 图

r - 将小数转换为R中的不同基数

删除 Shiny 数据表excel输出中标题上方的 "title"行?

java - Spring Reactive Web - 异常总是包含在 500 中