简体   繁体   中英

Message within function (for status) not showing immediately in console

I have written a function, which takes some time to run (due to a 1000+ loop on a huge dataset in combination with forecasting model testing).

To have any idea on the status, while the function is called, I use the message command inside the for-loop in the function. The problem is that all the messages are shown in the console after the function is finished, instead of showing immediately. So it doesn't help me :)

I tried to find a solution on Stackoverflow, but didn't found one. I looked for instance on the question " showing a status message in R ". All answers and example codes in that topic still give me only text in the console after a function is processed instead of immediately.

How to solve this? Is there maybe a setting in R which prevents immediate printing of message text in the console?

note: examples I tried below, which give the same results as my function; showing text after processing the function.

example1 (Joshua Ulrich):

for(i in 1:10) {
  Sys.sleep(0.2)
  # Dirk says using cat() like this is naughty ;-)
  #cat(i,"\r")
  # So you can use message() like this, thanks to Sharpie's
  # comment to use appendLF=FALSE.
  message(i,"\r",appendLF=FALSE)
  flush.console()
}

example2 (Tyler):

test.message <- function() {
  for (i in 1:9){
    cat(i)
    Sys.sleep(1)
    cat("\b")
  }
}

edit: the first example does work ('flush console' was the problem)...but when I tested it, I commented out flush console for some reason :S

test.message <- function() {
     for (i in 1:9){
       cat(paste(as.character(i),'\n'))
       flush.console()
       Sys.sleep(1)
     }
   }

which is similar to the recommendation by fotNelton.

Edit: ttmaccer is most likely right. I've just tested on a Ubuntu server and the code works without flushing the console.

I seem to think this maybe a windows specific problem. On linux or running R in a cygwin shell the flush.console() may not be needed.

You may be interested in using one of the progress bar functions ( winProgressBar , tkProgressBar , or txtProgressBar ). The win version only works on windows, but the win and tk versions have the advantage that they do not clutter your output, but rather open another small window and display the progress there.

The progress through a loop can be shown with the progress bar, but other detailed information can be updated and shown with the label argument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM