How to output text in the R console without creating new lines?

RNewlineRstudioOutput Formatting

R Problem Overview


I would like to output a progress indicator during my lengthy running algorithms. I can easily "bubble up" a progress value from within my algorithm (e.g. via invoking a provided function callback specifically for this purpose), but the difficulty is in the actual text output process. Every call to print creates a new line, and each prefixed with [1].

Is there a way to print at different moments in time, without introducing line breaks?

To be concrete, I want to achieve an "animation" that would look like the following if observed at two different times.

0%...

...

0%...2%...4%...

R Solutions


Solution 1 - R

Use cat() instead of print():

cat("0%")
cat("..10%")

Outputs:

0%..10%

Solution 2 - R

Bah, Andrie beat me to it by 28 seconds.

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

Solution 3 - R

Maybe you can yse plyr

  l_ply(1:4,function(x) x+1,.progress= progress_text(char = '+'),.print=TRUE)
  |                                 |   0%[1] 2
  |++++++                           |  25%[1] 3
  |+++++++++++++++                  |  50%[1] 4
  |++++++++++++++++++++++           |  75%[1] 5
  |++++++++++++++++++++++++++++++++ |  100%[1]

Solution 4 - R

If you really need a progress bar as such, use txtProgressBar for console output. Or winProgressBar under Windows for a windowed progress bar.

Solution 5 - R

I believe that you are looking for \r in the cat function like below:

for(i in 1:100) {
	cat('\r',
			i,
			'% |',
			rep('=', i / 4),
			ifelse(i == 100, '|\n',  '>'), sep = '')
	Sys.sleep(.1)
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDuckMaestroView Question on Stackoverflow
Solution 1 - RAndrieView Answer on Stackoverflow
Solution 2 - RRoman LuštrikView Answer on Stackoverflow
Solution 3 - RagstudyView Answer on Stackoverflow
Solution 4 - RStephan KolassaView Answer on Stackoverflow
Solution 5 - RTPArrowView Answer on Stackoverflow