Search code examples
textshinyprintingrstudio

How to print several texts in a window in R in a for loop, so that the text replaces the previous one at each iteration?


I want to print a text in a window with using a loop such as the following one

texts <- c("a", "ab", "abd")
for (t in texts) {
  cat(t, "\n")
  Sys.sleep(1.5) # The real transition time is around 0.05 second
}

enter image description here

  • I want the text at each iteration to replace the previous one, I don't want the text to be added vertically
  • I want the text to appear in a new window, not in the console of RStudio

Do I have to resort to Shiny? How to do it?


Solution

  • vcat <- function(...) {
      require(htmltools)
      html_print(pre(paste0(capture.output(cat(...)), collapse="\n")))
    }
    
    texts <- c("a", "ab", "abd")
    for (t in texts) {
      vcat(t, "\n")
      Sys.sleep(1.5)
    }
    

    enter image description here

    Code taken from this answer