C.Robin
C.Robin

Reputation: 1102

output from print() replacing itself on each iteration of a loop in R

Is it possible for the output of a print() call within a loop to replace itself in the console / interactive markdown file on each iteration of a loop? I do all my R coding in RStudio if that's important.

For example, this is the behaviour I observe currently:

for (i in 1:20){
 print(paste('iteration', i)) 
}  

[1] "iteration 1"
[1] "iteration 2"
[1] "iteration 3"
[1] "iteration 4"
[1] "iteration 5"
[1] "iteration 6"
[1] "iteration 7"
[1] "iteration 8"
[1] "iteration 9"
[1] "iteration 10"
[1] "iteration 11"
[1] "iteration 12"
[1] "iteration 13"
[1] "iteration 14"
[1] "iteration 15"
[1] "iteration 16"
[1] "iteration 17"
[1] "iteration 18"
[1] "iteration 19"
[1] "iteration 20"

With a relatively small number of iterations this isn't that bad, but I do like to print out the iteration so I can keep track of it -- and especially when there is a large number of iterations. So is there a way to print iteration 1 on the first iteration and then replace that text with iteration 2 and so on?

In Python, I mostly use Jupyter and you can achieve this by importing the clear_output function from IPython.display and then calling it immediately ahead of calling print() on each iteration. E.g.

from IPython.display import display, clear_output
for i in range(1, 21):
    clear_output(wait=True)
    print('iteration', i)

Is there anything like this in R/RStudio?

Upvotes: 4

Views: 1032

Answers (1)

r2evans
r2evans

Reputation: 160447

You can use cat and the \r linefeed (but no \n newline) character.

for (i in 1:3) {
  cat(paste("\riteration", i))
  Sys.sleep(1)
}
cat("\n")

Upvotes: 5

Related Questions