Is there a way to update existing text in the R console?

r

Solution

Flushing the console works but may cause flickering. If you want a very simple text line update, then it’s sufficient to go back to the beginning of the line by printing `\r` and to overwrite the text there.

Here’s a `progress` function from the `rcane` module:

progress <- function (x, max = 100) {
    percent <- x / max * 100
    cat(sprintf('\r[%-50s] %d%%',
                paste(rep('=', percent / 2), collapse = ''),
                floor(percent)))
    if (x == max)
        cat('\n')
}

Here’s a screenshot of the progress bar in action:

And finally, this can be wrapped nicely so that its usage is effortless:

map_with_progress(some_function, some_data)

(See the link above for an implementation; of course R’s own `txtprogressBar` is quite a bit more flexible.)

Problem

I am wondering if it is possible to update existing text in the R console? E.g., if I run a function that takes a bit longer to execute, I would like to know how far along it is currently. I could achieve this by issuing `print("at 10%")`, `print("at 20%")`, etc. at appropriate locations in the function. But this could be a relatively long output, since it produces a new line each time. Is there a way to update the console text from the running function in a way that it updates the current line in the console and not create a new line? E.g. `>at 10%` in the console changes to `>at 20%` when appropriate.

Original source