How to provide a tidy R console update message in RStudio?
r, rstudio
Solution
Do you require the actual values/message or are you just trying to show progress?
If it's the latter, `txtProgressBar()` might be enough:
imax <- 2000
msg <- txtProgressBar(min=1, max=length(seq_len(imax)), initial=1)
for (i in seq_len(imax)) {
setTxtProgressBar(msg, i)
Sys.sleep(0.001) # so it will show something vs just fly through the loop
}
close(msg)
If you need the values/message and are OK with just not having it be an actual diagnostic message, then `cat` should do it:
imax <- 2000
for (i in seq_len(imax)) {
mess <- sprintf("slightly different length message: %i", i)
cat(paste(rep("\b", nchar(mess)), collapse = ""))
cat(mess)
if (i == imax) { cat("\n") }
Sys.sleep(0.001) # again, loop is too fast to show w/o a delay
}
EDIT/addition from original submission:
Did some additional testing and it's the output to `stderr` that's causing the different behavior in RStudio's console area. When I call `.makeMessage` directly and then use `cat` with output going to `stdout` vs `stderr` it works:
imax <- 2000
for (i in seq_len(imax)) {
mess <- sprintf("slightly different length message: %i", i)
cat(.makeMessage(paste(rep("\b", nchar(mess)), collapse = ""), domain=NA, appendLF = FALSE))
cat(.makeMessage(mess, domain=NA, appendLF = (i == imax)))
Sys.sleep(0.001) # delay...see above snippets
flush.console()
}
add `file=stderr()` to the `cat`'s and it will behave the way the original `message` call does.
Problem
This code lets me leave a nice message (on Windows) in the R console, without fill up the screen: ``` imax <- 2000 for (i in seq_len(imax)) { mess <- sprintf("slightly different length message: %i", i) message(paste(rep("\b", nchar(mess)), collapse = ""), appendLF = FALSE) message(mess, appendLF = i == imax) flush.console() } ``` In RStudio the backspace character doesn't work and I get horrible appended messages everywhere. How can I do this nicely in both Rgui and RStudio? What about cross-platform?