R progress indicators

[This article was first published on binfalse » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Complicated calculations usually take a lot of time. So how to know the progress status to estimate how much time the program still needs to finish?

So far, I always printed some debugging stuff. So I knew how much is done and what is still to do, but that isn’t a nice solution if you plan to share your application with others (the guys in your dev team or the whole public in general).

The first solutions to indicate the status is just printing something like an iteration number:

1
2
3
4
5
6
steps <- 50
for (i in 1:steps)
{
    print (paste (i, “of”, steps))
    Sys.sleep (.1)
}

Ok, works but sucks 😉
Some days ago I read about an Unicode trick to build a clock on the prompt. Using this the next possibility for status indication is:

1
2
3
4
5
6
7
steps <- 50
for (i in 1:steps)
{
    cat (\r, 100*i/steps, “% “, sep=“”)
    Sys.sleep (.1)
}
cat (\n)

It’s much less line consuming. Of course there is also a lot of space to prettify it, for example:

1
2
3
4
5
6
7
steps <- 50
for (i in 1:steps)
{
    cat (\r, paste (paste (rep (“O”, 100*i/steps), collapse=“”), “o”, paste (rep (” “, 100 100*i/steps), collapse=“”),” “, 100*i/steps, “% “,sep=“”))
    Sys.sleep (.1)
}
cat (\n)

In order to write this article I searched for some more solutions and found one that, more or less, equals my last piece of code. txtProgressBar is part of the built-in R.utils package:

1
2
3
4
5
6
7
steps <- 50
bar <- txtProgressBar (min=0, max=steps, style=3)
for (i in 1:steps)
{
    setTxtProgressBar (bar, i)
    Sys.sleep (.1)
}

The last progress bar I want to present is a visual one and comes with the package tcltk:

1
2
3
4
5
6
7
8
9
steps <- 50
library (“tcltk”)
bar <- tkProgressBar (title=“my small progress bar”, min=0, max=steps, width=300)
for (i in 1:steps)
{
    setTkProgressBar (bar, i, label=paste(round(i/steps*100, 0), “%”))
    Sys.sleep (.1)
}
close(bar)

The code for this article is attached.

Download:
R: progressbars.R
(Please take a look at the man-page)

To leave a comment for the author, please follow the link and comment on their blog: binfalse » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)