Wednesday, February 20, 2013

Progress bar in R


A decent percentage of working time in R, I spend looping over chromosomes, transcription factors or tissues, usually, using parallelization.

To get the stuff to run simultaneously I use the foreach function from the doMC package, and for monitoring of the progress of the execution, I made use of the cat/print functions, which mostly just clutter the terminal.

Today a friend of mine set me a link to this blog, and I was dumbfounded when I read that the R base package has an inbuilt function for a nice looking progress bar. To my luck, it works perfectly when put inside a foreach loop.

library(doMC)
registerDoMC(5)
total <- 200
# create progress bar
pb <- txtProgressBar(min = 0, max = total, style = 3)
foreach(i = 1:total)%dopar%{
   Sys.sleep(0.1)
   setTxtProgressBar(pb, i)
}

close(pb)

6 comments:

  1. I'm not sure if it fits your purposes, but the plyr package is build on foreach, and adds nice alternatives to the apply/lapply functions. The function's have built-in parallel options and progress bars :)

    ReplyDelete
    Replies
    1. It seems I overlooked, a bit, the functionality of the plyr package.
      This is going to make an awesome addition to my code!
      Tnx!

      Delete
  2. I was trying to automate the call to the progressbar on SO, in which question you might be also interested: http://stackoverflow.com/questions/7349570/wrapper-to-for-loops-with-progress-bar

    ReplyDelete
  3. you should close the progressbar by close(pb) after the loop.

    ReplyDelete