Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't print to console from within while-loop in R

I am running this piece of code from a Rgui.exe window in Windows:

i = 1
while(i <= 10){
    cat(i, "\n") 
    i = i + 1
    Sys.sleep(2)
}

The cat() piece does not get output every 2 seconds, but only collectively at the end of the 20 seconds, i.e. 10 iterations.

I am used to print() and cat() calls getting output immediately, so I don't know why this is happening here.

How do I make R print immediately in each iteration?

like image 575
Alexander Engelhardt Avatar asked Dec 08 '25 08:12

Alexander Engelhardt


1 Answers

It's "output buffering"; try flush.console() after using cat. From the help page:

This does nothing except on console-based versions of R. On the macOS and Windows GUIs, it ensures that the display of output in the console is current, even if output buffering is on.

like image 111
Aaron left Stack Overflow Avatar answered Dec 09 '25 23:12

Aaron left Stack Overflow