How to flush the print buffer in R?

Viewed 5183

I want to run a long-running simulation and have updates printed periodically. However, I am finding that my print statements are being buffered, even when I explicitly try to flush. Here, for example:

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

I would expect this to increment every 1sec, but it outputs everything at the end, after 10 seconds.

How would you force a flush of the print buffer?

2 Answers

You can also use cat():

for (i in 1:10) {

  # Sleep for 1 second
  Sys.sleep(1)

  # Print the current iteration
  cat(paste0("\r", i))      
}
Related