Search code examples
rprinting

Printing repetitively on the same line in R


I was wondering what is the best way in R to keep printing on the same line in a loop to avoid swamping your console? Let's say to print a value indicating your progress, as in

for (i in 1:10) {print(i)}

Edit:

I tried inserting carriage returns before each value as in

for (i in 1:10000) {cat("\r",i)}

but that also doesn't quite work as it will just update the value on the screen after the loop, just returning 10000 in this case.... Any thoughts?

NB this is not to make a progress bar, as I know there are various features for that, but just to be able to print some info during the progression of some loop without swamping the console


Solution

  • You have the answer, it's just looping too quickly for you to see. Try:

    for (i in 1:10) {Sys.sleep(1); cat("\r",i)}
    

    EDIT: Actually, this is very close to @Simon O'Hanlon's answer, but given the confusion in the comments and the fact that it isn't exactly the same, I'll leave it here.