Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing repetetively on the same line in R

Tags:

r

printing

I was just wondering what is the best way in R to keep on 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

like image 354
Tom Wenseleers Avatar asked Jan 10 '14 10:01

Tom Wenseleers


People also ask

How do I print numbers on the same line in R?

You can use the cat() function to easily print multiple variables on the same line in R. This function uses the following basic syntax: cat(variable1, variable2, variable3, ...)

How do I print certain variables in R?

Print output using sprintf() function This function returns a character vector containing a formatted combination of string and variable to be printed. Syntax: sprintf(“any string %d”, variable) or, sprintf(“any string %s”, variable) or, sprintf(“any string %f”, variable)) etc.

How do I print the next line in R?

The most commonly used are "\t" for TAB, "\n" for new-line, and "\\" for a (single) backslash character.

How do you print a sentence in R?

To display ( or print) a text with R, use either the R-command cat() or print(). Note that in each case, the text is considered by R as a script, so it should be in quotes. Note there is subtle difference between the two commands so type on your prompt help(cat) and help(print) to see the difference.


2 Answers

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.

like image 65
BrodieG Avatar answered Oct 12 '22 15:10

BrodieG


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 horses mouth).

To repeatedly print in the same place, you need to clear the console. I am not aware of another way to do this, but thanks to this great answer this works (in RStudio on Windows at least):

for (i in 1:1e3) {
  cat( i )
  Sys.sleep(0.01)
  cat("\014")
}
like image 32
Simon O'Hanlon Avatar answered Oct 12 '22 14:10

Simon O'Hanlon