Wrapper to FOR loops with progress bar

前端 未结 8 675
走了就别回头了
走了就别回头了 2021-01-31 19:57

I like to use a progress bar while running slow for loops. This could be done easily with several helpers, but I do like the tkProgressBar from tcl

8条回答
  •  执笔经年
    2021-01-31 20:16

    Given the other answers supplied, I suspect that it is impossible tough to do in exactly the way you specify.

    However, I believe there is a way of getting very close, if you use the plyr package creatively. The trick is to use l_ply which takes a list as input and creates no output.

    The only real differences between this solution and your specification is that in a for loop you can directly modify variables in the same environment. Using l_ply you need to send a function, so you will have to be more careful if you want to modify stuff in the parent environment.

    Try the following:

    library(plyr)
    forp <- function(i, .fun){
      l_ply(i, .fun, .progress="tk")
    }
    
    a <- 0
    forp(1:100, function(i){
      Sys.sleep(0.01)
      a<<-a+i
      })
    print(a)
    [1] 5050
    

    This creates a progress bar and modifies the value of a in the global environment.


    EDIT.

    For the avoidance of doubt: The argument .fun will always be a function with a single argument, e.g. .fun=function(i){...}.

    For example:

    for(i in 1:10){expr} is equivalent to forp(1:10, function(i){expr})

    In other words:

    • i is the looping parameter of the loop
    • .fun is a function with a single argument i

提交回复
热议问题