I have been playing around with the R function txtProgressBar(). How can I hijack the function\'s ability to overwrite the current output in the console?
i.e. the p
In case you want to use the function message
to print something, you can set its parameter appendLF
to FALSE to avoid it printing a new line and then the use the carriage return ('\r')
character to return to the start of the line, for example:
for (i in 1:5) {
message('\r', i, appendLF = FALSE)
}
This program seems to work:
while (1) {
cat('\b\b\b\b\b\b',format(Sys.time(),'%H:%M'))
flush.console()
}
Are there any reasons this might be a bad idea?
/edit: even better (thanks @Greg Snow):
while (1) {
cat('\r',format(Sys.time(),'%H:%M:%S'))
flush.console()
}
Sure you can:
while(1) {
cat("\b\b\b\b\b\b\b\b",format(Sys.time(), "%H:%M:%S"),sep="")
}
Instead of "\b\b\b\b" you can just use "\r" to go to the beginning of the line and overwrite everything on the line (make sure to still use cat and don't put in a line feed).
Though if you want to display progress it might be better to use winProgressBar (windows only) or tkProgressBar (tcltk package, all platforms) which can be updated with a label in addition to the progress bar.
On windows you can also use the setWindowTitle or setStatusBar functions to put that type of information into the top or bottom of the larger window.
I do not think overwriting is possible on the console. There is no backspace escape sequence. The progress bar can be drawn because the cat function will not emit a cr
unless told to do so.
Edit: I was wrong. The backspace character is recognized:
for (i in 1:1000) {
cat(as.character(Sys.time()))
flush.console()
for(i in 1:19) {cat("\8")} }