R在控制台中显示堆叠的两个进度条(带代码)

时间:2018-03-10 06:07:44

标签: r function console progress-bar progress

有可能做到这一点吗?我想同时在R中垂直堆叠显示两个进度条,因为函数在另一个更大的函数中运行。

一个是函数中较大函数的整体进程状态,另一个是函数中的各个进程(下载等)。

  1. 如果可能的话,我想使用进度包的progress_bar(如果不可能的话,基础或任何解决方案都很酷!:)

  2. 我想留在控制台,而不是使用tk或类似的解决方案绘制进度条(https://www.r-bloggers.com/multiple-progress-bars/

  3. 提前致谢!

    以下示例在进度(首选)和基础R中模仿所需的功能和结果:

     ###Example in progress package(preferred)
    library(progress)
    
    ###Create the progress bars
    overallbar <- progress_bar$new(
      format = " downloading :what [:bar] :percent Guestimated Remaining OVERALL: :eta",
      clear = FALSE, total = 1000, width = 60)
    statusbar <- progress_bar$new(
      format = " [:bar] :percent Guestimated Remaining CURRENT FILE: :eta",
      clear = FALSE, total = 100, width = 60)
    
    ###Only displays the statusbar when I'd like to display both
    
    for (i in 1:1000) {
      overallbar$tick()
      statusbar$tick()
      Sys.sleep(1 / 1000)
    }
    
    ###Desired outcome (imitation only)
    downloading THIS FILE NOW [] 100% Guestimated remaining OVERALL:  0s
    [============] 100% Guestimated remaining CURRENT FILE:  0s
    

    使用基础R INSTEAD的示例(比进度包样式更不可取):

    ###Base R
    pb1   <- txtProgressBar(1, 1000, style=3)
    pb2   <- txtProgressBar(title="File Progress",1, 100, style=3)
    
    
    ###Like progress, base also only displays the second progress bar 
    
    cat("OVERALL PROGRESS:")
    for (i in 1:1000) {
      setTxtProgressBar(pb1, i)
      ###something is funky with the title option, not working
      ###I usually use progress package, you get the idea, I'd like a title
      setTxtProgressBar(title="File Progress:", pb2, i)
      Sys.sleep(1 / 1000)
    }
    
    ###Desired outcome (imitation only)
    
    OVERALL PROGRESS:
    |========================================================================================| 100%
    File Progress:
    |========================================================================================| 100%
    

1 个答案:

答案 0 :(得分:2)

至少在Base R的情况下,进度条只需重新绘制同一条线即可。您可以使用ANSI转义序列在行之间跳转。修改你的Base R例子,

cat("OVERALL PROGRESS:\n\n") # 2 newlines leaving a blank between headers
cat("File Progress:\n") # 1 newline leaves in position for pb2
for (i in 1:1000) {
  cat("\033[2A")   # up 2 lines for pb1
  setTxtProgressBar(pb1, i)
  cat("\033[2B")   # down 2 lines for pb2
  setTxtProgressBar(title="File Progress:", pb2, i)
  Sys.sleep(1 / 1000)
}
cat("\033[2B\n") # for good measure

这适用于Linux,可能也适用于MacOS终端,maybe even Windows虽然我没有在那里进行测试。