Reprint on one line in R

I'm just wondering what is the best way in R to keep printing on the same line in a loop so as not to put out your console? Let them say to print a value indicating your progress, as in

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

Edit:

I tried inserting a carriage return before each value, as in

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

but it 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 does not mean to make a progress bar, because I know that there are different functions for this, but just to be able to print some information during the progression of a cycle without dulling the console.

+7
r printing
source share
3 answers

You have an answer, it just goes too fast for you. 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 clutter in the comments and the fact that this is not quite the same, I will leave it here.

+6
source share

Try using cat() ...

 for (i in 1:10) {cat(paste(i," "))} #1 2 3 4 5 6 7 8 9 10 

cat() performs much less conversion than print() (from the mouth of horses).

To reprint in the same place, you need to clean the console. I don't know another way to do this, but thanks to this excellent answer, this works (at least in RStudio on Windows):

 for (i in 1:1e3) { cat( i ) Sys.sleep(0.01) cat("\014") } 
+1
source share

Well ... are you worried about freezes or just being notified of the completion of work?

In the first case, I will stick with w / my j%%N , where N is big enough so you don't load the console.

In the second case, add the final line to your script or function, which, for example, calls "Beep".

0
source share

All Articles