Display a counter for loops across one display line

12,679

Solution 1

Try to use the function flush.console()

for (i in 1:10){
 cat(paste(i, " ")); flush.console()
}

gives

1  2  3  4  5  6  7  8  9  10

Here a small modification to the code that will print only one single number and increment it with each run. It uses a carriage return (\r) sequence to avoid a long list of numbers in the console.

for(i in 1:100) {  
  Sys.sleep(.1)      # some loop operations
  cat(i, "of 100\r") 
  flush.console()
}

Solution 2

look at the functions txtProgressBar, winProgressBar (windows only), and tkProgressBar (tcltk package) as other ways of showing your progress in a loop.

On some consoles you can also use "\r" or "\b" in a cat statement to go back to the beginning of the line and overwrite the previous iteration number.

Solution 3

If you're interested, here are some progress bar examples:

http://ryouready.wordpress.com/2009/03/16/r-monitor-function-progress-with-a-progress-bar/

http://ryouready.wordpress.com/2010/01/11/progress-bars-in-r-part-ii-a-wrapper-for-apply-functions/

Solution 4

Try this for simple loops:

 for(i in 1:100){
    Sys.sleep(.1) # Your code here
    cat("\r", i, "of", 100) 
    flush.console()
 }

Or this for nested loops:

for(i in 1:100){
  for(j in 1:100){
    Sys.sleep(.1)  # Your code here
    cat("\r", i, ".", j, "of", 100, "\r") 
    flush.console()
  }
}
Share:
12,679
Cyrus S
Author by

Cyrus S

Updated on June 15, 2022

Comments

  • Cyrus S
    Cyrus S almost 2 years

    I am running loops in R of the following variety:

    for(i in 1:N){...}
    

    I would like to have a counter that displays the current value of i in the progress of the loop. I want this to keep track of how far along I am toward reaching the end of the loop. One way to do this is to simply insert print(i) into the loop code. E.g.,

    for(i in 1:N){
    ...substantive code that does not print anything...
    print(i)
    }
    

    This does the job, giving you the i's that is running. The problem is that it prints each value on a new line, a la,

    [1] 1
    [1] 2
    [1] 3
    

    This eats up lots of console space; if N is large it will eat up all the console space. I would like to have a counter that does not eat up so much console space. (Sometimes it's nice to be able to scroll up the console to check to be sure you are running what you think you are running.) So, I'd like to have a counter that displays as,

    [1] 1 2 3 ...
    

    continuing onto a new line once the console width has been reached. I have seen this from time to time. Any tricks for making that happen?

  • Cyrus S
    Cyrus S about 13 years
    True that it doesn't quite wrap appropriately. It is working for my needs for the time being, so thanks @Mark, but if there is a better wrap option that would be great.