PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, September 18, 2022

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

 September 18, 2022     for-loop, loops, printing, r     No comments   

Issue

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

Solution

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)


Answered By - Jouni Helske
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing