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
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, ...)
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.
The most commonly used are "\t" for TAB, "\n" for new-line, and "\\" for a (single) backslash character.
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.
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.
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")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With