如何在 R 闪亮的 for 循环内更新反应性输出 [英] How to update reactive output inside a for loop in R shiny
问题描述
我是 Shiny 的新手,遇到了一个我找不到答案的问题.基本上,我有一个 Shiny 应用程序,它在循环中进行一些长时间的计算,我希望它每隔几次迭代就输出一个进度报告".然而,即使我在循环中重新分配了我的反应变量,输出也不会更新,直到循环(或整个函数?)完成.
这是我的意思的简化测试用例:
图书馆(闪亮)# 基本界面ui <-流体页面(动作按钮(运行",运行"),文本输出(文本框"))# 带循环的基本服务器服务器 <- 功能(输入,输出){textvals=reactiveValues(a=0)观察事件(输入$运行,{for(i 在 1:10){textvals$a=i # 期望输出在这里更新,但不会Sys.sleep(0.1) # 轻微的暂停所以不是瞬间的}})output$textbox <- renderText({文本值$a})}# 运行应用程序闪亮应用(用户界面 = 用户界面,服务器 = 服务器)
我期望的是,当循环执行时,显示会更新 1, 2, 3, ... 10.相反,它只是直接从 0 跳转到 10.如何在循环中途强制更新?
谢谢.
使用 invalidateLater
你可以得到一些接近你想要的东西.我认为这不是最短的方法,但它可以帮助您找到更好的解决方案.
图书馆(闪亮)# 基本界面ui <-流体页面(动作按钮(运行",运行"),文本输出(文本框"))# 带循环的基本服务器服务器 <- 功能(输入,输出,会话){textvals <-reactiveVal(0)主动 <-reactiveVal(FALSE)output$textbox <- renderText({文本值()})观察({invalidateLater(1000,会话)隔离({如果(活动()){textvals(textvals() + 1)如果(textvals()> 9){活动(假)}}})})观察事件(输入$运行,{活动(真)})}# 运行应用程序闪亮应用(用户界面 = 用户界面,服务器 = 服务器)
顺便说一下,reactive 和 for 循环不太好相处.这可能会有所帮助:https://gist.github.com/bborgesr/e1ce7305f914f9ca762ea6>
I'm new to Shiny and have hit a problem I can't find an answer for. Basically, I have a Shiny app that does some long calculations in a loop and I want it to output a "progress report" every few iterations. However, even though I reassign my reactive variable within the loop, the output doesn't update until the loop (or entire function?) has finished.
Here is a simplified test case of what I mean:
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)
What I would expect is that the display would update 1, 2, 3, ... 10 as the loop executes. Instead, it just jumps straight from 0 to 10. How can I force an update partway through the loop?
Thank you.
With using invalidateLater
you can get something closed to what you want. Not the shortest way to do it I think, but it may help you to find a better solution.
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)
By the way, reactive and for loops don't really get on well. This may help : https://gist.github.com/bborgesr/e1ce7305f914f9ca762c69509dda632e
这篇关于如何在 R 闪亮的 for 循环内更新反应性输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!