Shiny应用进度条不推进问题排查求助
问题原因分析
你的进度条无法推进的核心原因有两个:
- 计算逻辑与进度控制分离:耗时的
MBESS::ci.reliability计算被放在eventReactive中,而withProgress仅在renderTable里触发result(),无法捕捉计算过程中的进度变化。 - 无进度更新触发:
withProgress初始化后没有调用incProgress()来更新进度值,导致进度条一直停留在初始状态。
解决方案
我们需要将计算逻辑整合到进度控制块内,同时利用ci.reliability的Bootstrap迭代次数(B参数)来分步更新进度。以下是修改后的完整代码:
library(shiny) library(shinydashboard) library(shinythemes) library(dplyr) library(MBESS) #Example of data to load df1 <- read.csv("https://raw.githubusercontent.com/jventural/Download/main/df1.csv", sep = ";") #ui.r ui <- fluidPage( sidebarLayout( # Main panel ---------------- sidebarPanel( sidebarMenu( menuItem("Calculadora", tabName = "sect_a") ) ), mainPanel( # Calculator ---------- tabItem( tabName = "sect_a", tabsetPanel( id="tabA", type = "tabs", tabPanel("Calculando omega", fileInput("datafile", "Choose CSV File", accept = ".csv"), actionButton(inputId = "click1", "Calcular"), fluidPage( HTML("<b> Nota: </b> El nombre de los items debe ser: Item1, Item2... etc") ) ), tabPanel("Output", tableOutput("modifiedData")) ) ) ) ) ) #server.r server = function(input, output) { output$modifiedData = renderTable({ req(input$click1, input$datafile) withProgress(message = 'Calculando', detail = 'Espera un momento...', value = 0, { raw_df <- read.csv(input$datafile$datapath, sep=",") item_data <- raw_df %>% select(starts_with("Item")) B <- 10 # 与ci.reliability的B参数保持一致 # 自定义进度更新函数,传递给ci.reliability的progress参数 update_progress <- function(current) { incProgress(1/B, detail = paste("Iteración", current, "de", B)) } IC <- MBESS::ci.reliability( data = item_data, N = nrow(raw_df), type = "categorical", interval.type = "perc", B = B, progress = update_progress # 传入进度更新函数 ) IC }) }) } shinyApp(ui, server)
关键修改说明
- 整合计算与进度控制:将数据读取、
ci.reliability计算全部放入withProgress块内,确保进度控制能覆盖整个计算流程。 - 利用内置进度参数:
MBESS::ci.reliability提供了progress参数,可以接收一个自定义函数,每次Bootstrap迭代时会传入当前迭代次数,我们通过这个函数调用incProgress(1/B)来更新进度条。 - 移除冗余的eventReactive:直接在
renderTable中处理计算,避免逻辑分离导致的进度无法追踪。
如果ci.reliability的progress参数不生效(部分旧版本可能存在兼容问题),可以手动模拟进度更新:
# 替代方案:手动模拟进度 IC <- NULL withProgress(message = 'Calculando', detail = 'Iniciando...', value = 0, { raw_df <- read.csv(input$datafile$datapath, sep=",") item_data <- raw_df %>% select(starts_with("Item")) B <- 10 # 先运行一次获取结果结构 IC <- MBESS::ci.reliability( data = item_data, N = nrow(raw_df), type = "categorical", interval.type = "perc", B = 1, progress = NULL ) # 模拟剩余迭代并更新进度 for(i in 2:B){ incProgress(1/B, detail = paste("Iteración", i, "de", B)) temp <- MBESS::ci.reliability( data = item_data, N = nrow(raw_df), type = "categorical", interval.type = "perc", B = 1, progress = NULL ) # 合并结果(根据ci.reliability的输出结构调整) IC$lower <- c(IC$lower, temp$lower) IC$upper <- c(IC$upper, temp$upper) } # 计算最终的百分位数区间 IC$lower <- quantile(IC$lower, 0.025) IC$upper <- quantile(IC$upper, 0.975) })
内容的提问来源于stack exchange,提问作者Jose VL
相关产品推荐
相关产品推荐

