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?
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With