Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display a counter for loops across one display line

Tags:

loops

r

counter

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?

like image 971
Cyrus S Avatar asked Mar 09 '11 16:03

Cyrus S


2 Answers

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()
}
like image 78
Mark Heckmann Avatar answered Nov 09 '22 18:11

Mark Heckmann


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.

like image 24
Greg Snow Avatar answered Nov 09 '22 19:11

Greg Snow