how Wrapper to FOR loops with progress bar



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 tcltk package.

A small example:

pb <- tkProgressBar(title = "Working hard:", min = 0, max = length(urls), width = 300)
for (i in 1:300) {
    setTkProgressBar(pb, i, label=paste( round(i/length(urls)*100, 0), "% ready!"))

And I would like to set up a small function to store in my .Rprofile named to forp (as: for loop with progressbar), to call just like for but with auto added progress bar – but unfortunately have no idea how to implement and grab the expr part of the loop function. I had some experiments with but without success 🙁

Imaginary working example (which acts like a for loop but creates a TkProgressBar and auto updates it in each iteration):

forp (i in 1:10) {
    #do something

UPDATE: I think the core of the question is how to write a function which no only have parameters in the parentheses after the function (like: foo(bar)), but also can handle expr specified after the closing parentheses, like: foo(bar) expr.

BOUNTY OFFER: would go to any answer that could modify my suggested function to work like the syntax of basic for loops. E.g. instead of

> forp(1:1000, {
+   a<-i
+ })
> a
[1] 1000

it could be called like:

> forp(1:1000) {
+   a<-i
+ }
> a
[1] 1000

Just to clarify the task again: how could we grab the { expression } part of a function call? I am afraid of that this is not possible, but will leave on the bounty for a few days for the pros 🙂






Facebook Comments

Post a comment