Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a variable inside a for loop to the console in real time as the loop is running?

I have a loop that takes a long time for each iteration, and I would like to see the progress of it in real time. How do I print a variable inside a for loop to the console in real time, as the loop is running? Each of these print everything after the loop is finished, which is useless for me:

for(i in 1:10){
  write(i,stdout())
}

for(i in 1:10){
  write(i,stderr())
}

for(i in 1:10){
  print(i)
}
1
2
3
4
5
6
7
8
9
10
like image 840
Eric Avatar asked Mar 28 '13 05:03

Eric


People also ask

Can you use variables in a for loop?

Yes you can use the same counter variable name for an inner for loop as for the outer for loop.

Can we use printf inside for loop?

It keeps the for loop running until y==0 . The printf in the afterthought is run at the end of each iteration but doesn't change the value of y . The loop's body does change y however. Most textbooks will describe this.

What is variable looping?

In computer programming, a loop variable is a variable that is set in order to execute some iterations of a "for" loop or other live structure. A loop variable is a classical fixture in programming that helps computers to handle repeated instructions.


2 Answers

The last one does print in real time, try it like this:

for(i in 1:10){
  Sys.sleep(0.1)
  print(i)
}

This looks fine in Rstudio, but in classic Rgui you have to click the console in order to it to refresh (increasing the sleep for example by Sys.sleep(0.5) helps to see that). You can circumvent that by using flush.console which clears the buffer:

for(i in 1:10){
  Sys.sleep(0.1)
  print(i)
  flush.console() 
}

Or in Windows you can select Misc in the upper toolbar and uncheck the buffered output.


If your goal is to track the process of your loop, the above method feels bit akward (at least to my eyes) when you are running through large number of iterations. In that case it might be nicer to use progress bars:

n<- 1000
pb <- txtProgressBar(min = 0, max = n, style = 3) #text based bar
for(i in 1:n){
   Sys.sleep(0.001) 
   setTxtProgressBar(pb, i)
}
close(pb)

Or something even nicer:

library(tcltk)
n<- 1000
pb <- tkProgressBar(title = "Doing something", min = 0, max = n, width = 200)
for(i in 1:n){
   Sys.sleep(0.001) 
   setTkProgressBar(pb, i, label=paste(round(i/n*100,1),"% done"))
}
close(pb)
like image 74
Jouni Helske Avatar answered Sep 22 '22 16:09

Jouni Helske


The cat() function allows you to make useful complex statements to keep track of progress in your script

for(i in 1:10){
  ptm0 <- proc.time()
  Sys.sleep(0.5)  
  ptm1=proc.time() - ptm0
  jnk=as.numeric(ptm1[3])
  cat('\n','It took ', jnk, "seconds to do iteration", i)
}

>It took  0.49 seconds to do iteration 1
like image 21
Lucas Fortini Avatar answered Sep 20 '22 16:09

Lucas Fortini