开发者

Display a counter for loops across one display line

I am running loops in R of the following var开发者_开发技巧iety:

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?


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()
}


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.


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/


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()
  }
}


Not a very nice solution, but you can try something like this in your loop :

cat(paste(i, ifelse(i %% 30 == 0,"\n"," ")))

But you have to adjust manually the 30 value to fit the width of your console.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜