Overwrite current output in the R console

后端 未结 5 858
醉梦人生
醉梦人生 2021-01-01 18:43

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

相关标签:
5条回答
  • 2021-01-01 19:23

    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)
    }
    
    0 讨论(0)
  • 2021-01-01 19:25

    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() 
    }
    
    0 讨论(0)
  • 2021-01-01 19:27

    Sure you can:

    while(1) {
      cat("\b\b\b\b\b\b\b\b",format(Sys.time(), "%H:%M:%S"),sep="")
    }
    
    0 讨论(0)
  • 2021-01-01 19:33

    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.

    0 讨论(0)
  • 2021-01-01 19:34

    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")} }
    
    0 讨论(0)
提交回复
热议问题