R: Text progress bar in for loop

后端 未结 2 1110
南旧
南旧 2020-12-14 01:49

I have some sample code which contains a for loop and creates some plots like this (my actual data creates several thousands of plots):

xy <- structure(li         


        
相关标签:
2条回答
  • 2020-12-14 02:11

    for progress bar to work you need a number to track your progress. that is one of the reasons as a general rule I prefer using for with (i in 1:length(ind)) instead of directly putting the object I want there. Alternatively you'll just create another stepi variable that you do stepi = stepi + 1 in every iteration.

    you first need to create the progressbar object outside the loop

    pb = txtProgressBar(min = 0, max = length(ind), initial = 0) 
    

    then inside you need to update with every iteration

    setTxtProgressBar(pb,stepi)
    

    or

    setTxtProgressBar(pb,i)
    

    This will work poorly if the loop also has print commands in it

    0 讨论(0)
  • 2020-12-14 02:27

    You could write a very simple one on the fly to show percent completed:

    n <- 100
    for (ii in 1:n) {
      cat(paste0(round(ii / n * 100), '% completed'))
      Sys.sleep(.05)
      if (ii == n) cat(': Done')
      else cat('\014')
    }
    # 50% completed
    

    Or one to replicate the text bar:

    n <- 100
    for (ii in 1:n) {
      width <- options()$width
      cat(paste0(rep('=', ii / n * width), collapse = ''))
      Sys.sleep(.05)
      if (ii == n) cat('\014Done')
      else cat('\014')
    }
    # ============================
    
    0 讨论(0)
提交回复
热议问题