R progress indicators

June 18, 2011
By

(This article was first published on binfalse » R, and kindly contributed to R-bloggers)

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 his blog: binfalse » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: , , , , , ,

Comments are closed.