You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为嵌套purrr::map调用同时显示独立进度条?

实现嵌套进度条双行显示

要让外层总进度条与内层块进度条同时固定显示,需要借助progress包手动控制进度条的输出位置,避免默认的单行覆盖问题。以下是修改后的可运行代码:

library(purrr)
library(progress)
library(stringr)

list_of_chunks <- list(
  c(1,2,3),
  c(4,5,6),
  c(7,8,9)
)
n_chunks <- length(list_of_chunks)

slow_process_per_item <- function(item) Sys.sleep(1)

# 初始化外层总进度条,设置不自动清除
overall_progress <- progress_bar$new(
  format = "Overall: [:bar] :percent | ETA: :eta",
  total = n_chunks,
  clear = FALSE,
  width = 60
)

process_per_chunk <- function(chunk_of_items, chunk_id) {
  # 更新外层进度条
  overall_progress$tick()
  
  # 初始化内层块进度条,通过回调换行到外层下方
  chunk_progress <- progress_bar$new(
    format = str_glue("Chunk #{chunk_id} of {n_chunks}: [:bar] :percent | ETA: :eta"),
    total = length(chunk_of_items),
    clear = FALSE,
    width = 60,
    callback = function(...) cat("\n")
  )
  
  # 遍历处理块内元素,逐次更新内层进度条
  walk(chunk_of_items, function(item) {
    slow_process_per_item(item)
    chunk_progress$tick()
  })
  
  # 内层完成后,用ANSI控制码将光标移回外层进度条行
  cat("\033[1A")
}

# 执行嵌套处理
iwalk(list_of_chunks, process_per_chunk)

核心细节:

  • 外层进度条设置clear = FALSE,确保不会被后续输出清除
  • 内层进度条通过callback在创建时自动换行,固定显示在外层下方
  • 内层处理完成后,用\033[1A将光标移回外层行,保证下一次外层进度更新位置正确
  • 放弃purrr自带的.progress参数,手动调用$tick()控制进度更新,避免自动覆盖行

内容的提问来源于stack exchange,提问作者Or Gadish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 19:08:29