Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Prevent `cat` from leaving characters after carriage return ("\r")

Problem

I’m working on a progress bar that mimics the timer from the {pbapply} package:

|++++ | 10% ~calculating

After the progress bar figures out how much time is remaining, the progress bar turns over:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

|+++++ | 12% ~22s

So far, I have been able to mimic this latter feature. However, when trying to add the ~calculating text, I achieve this result:

|+++++ | 12% ~22sulating

I would like to make calculating disappear and not leave text over so that only ~22s is displayed.

Toy example

A toy example of this behavior is demonstrated here:

# Toy example
for(i in 1:100){
  
  # Sleep for a quarter second
  Sys.sleep(0.25)
  
  # Update progress
  if(i < 10){
    
    cat(
      sprintf(
        paste0("\r |%-49s| %s"), # Timer setup
        paste(rep("+", i / 2), collapse = ""), # Internal fill
        paste0(i, "% ~calculating") # Percent complete and time remaining
      )
    )
    
  }else{
    
    # Timing
    timing <- round((100 - i) * 0.25)
    
    cat(
      sprintf(
        paste0("\r |%-49s| %s"), # Timer setup
        paste(rep("+", i / 2), collapse = ""), # Internal fill
        paste0(i, "% ~", timing, "s") # Percent complete and time remaining
      )
    )
  }
  
}

Question

How can I avoid ~22sulating and instead have 22s while keeping the preliminary ~calculating?

Things I’ve tried:

\f = flushes entire console

flush.console() = does nothing as far as I can tell

>Solution :

Seems like you need enough whitespace characters asfter the "s" to cover up the string "ulating".

paste0(i, "% ~", timing, "s       ")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading