Alexander Engelhardt
Alexander Engelhardt

Reputation: 1712

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?

Upvotes: 3

Views: 1365

Answers (1)

Aaron - mostly inactive
Aaron - mostly inactive

Reputation: 37754

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.

Upvotes: 2

Related Questions