Showing a Status Message in R

showing a status message in R

How about something like this?

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()
}

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

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.

Dynamic status message from inside a for loop

If it is OK to clear the console each time, you can:

for (i in 1:1000) {
for(j in 1:1000){
for(k in 1:1000){
cat(paste('\014',i, j, k))
}
}
}

dplyr top_n() - Suppress status message?

That message appears when you don't explicitly pass a wt parameter to top_n to tell it which column to use select the top values for.

Compare

dd <- data.frame(x = c(10, 4, 1, 6, 3, 1, 1)) 
dd %>% top_n(2)
# Selecting by x
dd %>% top_n(2, x) # use column name

Ability to print a message in R console to indicate function is successful?

You can use message or cat or print. If you use message, someone else has the option of invoking your function wrapped with suppressMessages(). cat is going to print to the terminal no matter what. Also, you have to end cat with a \n if you want the CRLF.

Messages are printed in red.

message("Function Ran Successfully")
cat("Function Ran Successfully\n")

If you want colored messages, use the crayon package

cat(crayon::green$bold("Function Ran Successfully\n"))

print is particularly useful if you want to print out a structure, rather than just a single string.

print(head(iris, 2))
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa

Why is message() a better choice than print() in R for writing a package?

TL;DR

You should use cat() when making the print.*() functions for S3 objects. For everything else, you should use message() unless the state of the program is problematic. e.g. bad error that is recoverable gives warning() vs. show stopping error uses stop().

Goal

The objective of this post is to provide feedback on the different output options a package developer has access to and how one should structure output that is potentially on a new object or based upon strings.

R Output Overview

The traditional output functions are:

  1. print()
  2. cat()
  3. message()
  4. warning()
  5. stop()

Now, the first two functions (print() and cat()) send their output to stdout or standard output. The last three functions (message(), warning(), and stop()) send their output to stderr or the standard error. That is, the result output from a command like lm() is sent to one file and the error output - if it exists - is sent to a completely separate file. This is particularly important for the user experience as diagnostics then are not cluttering the output of the results in log files and errors are then available to search through quickly.

Designing for Users and External Packages

Now, the above is framed more in a I/O mindset and not necessarily a user-facing frameset. So, let's provide some motivation for it in the context of an everyday R user. In particular, by using 3-5 or the stderr functions, their output is able to be suppressed without tinkering with the console text via sink() or capture.output(). The suppression normally comes in the form of suppressWarnings(), suppressMessages(), suppressPackageStartupMessages(), and so on. Thus, users are only confronted with result facing output. This is particularly important if you plan to allow users the flexibility of turning off text-based output when creating dynamic documents via either knitr, rmarkdown, or Sweave.

In particular, knitr offers chunk options such as error = F, message = F, and warning = F. This enables the reduction of text accompanying a command in the document. Furthermore, this prevents the need from using the results = "hide" option that would disable all output.

Specifics of Output

print()

Up first, we have an oldie but a goodie, print(). This function has some severe limitations. One of them being the lack of embedded concatenation of terms. The second, and probably more severe, is the fact that each output is preceded by [x] followed by quotations around the actual content. The x in this case refers to the element number being printed. This is helpful for debugging purposes, but outside of that it doesn't serve any purpose.

e.g.

print("Hello!")

[1] "Hello!"

For concatenation, we rely upon the paste() function working in sync with print():

print(paste("Hello","World!"))

[1] "Hello World!"

Alternatively, one can use the paste0(...) function in place of paste(...) to avoid the default use of a space between elements governed by paste()'s sep = " " parameter. (a.k.a concatenation without spaces)

e.g.

print(paste0("Hello","World!"))

[1] "HelloWorld!"

print(paste("Hello","World!", sep = ""))

[1] "HelloWorld!"

cat()

On the flip side, cat() addresses all of these critiques. Most notably, the sep=" " parameter of the paste() functionality is built in allowing one to skip writing paste() within cat(). However, the cat() function's only downside is you have to force new lines via \n appended at the end or fill = TRUE (uses default print width).

e.g.

cat("Hello!\n")
Hello!

cat("Hello","World!\n")
Hello World!

cat("Hello","World!\n", sep = "")
HelloWorld!

It is for this very reason why you should use cat() when designing a print.*() S3 method.

message()

The message() function is one step better than even cat()! The reason why is the output is distinct from traditional plain text as it is directed to stderr instead of stdout. E.g. They changed the color from standard black output to red output to catch the users eye.

Message Output

Furthermore, you have the built in paste0() functionality.

message("Hello ","World!") # Note the space after Hello
"Hello World!"

Moreover, message() provides an error state that can be used with tryCatch()

e.g.

 tryCatch(message("hello\n"), message=function(e){cat("goodbye\n")})
goodbye

warning()

The warning() function is not something to use casually. The warning function is differentiated from the message function primarily by having a line prefixed to it ("Warning message:") and its state is consider to be problematic.

warning output

Misc: Casual use in a function may inadvertently trigger heartbreak while trying to upload the package to CRAN due to the example checks and warnings normally being treated as "errors".

stop()

Last but not least, we have stop(). This takes warnings to the next level by completely killing the task at hand and returning control back to the user. Furthermore, it has the most serious prefix with the term "Error:" being added.

Error Output

R: Text progress bar in for loop

for progress bar to work you need a number to track your progress. that is one of the reasons as a general rule I prefer using for with (i in 1:length(ind)) instead of directly putting the object I want there. Alternatively you'll just create another stepi variable that you do stepi = stepi + 1 in every iteration.

you first need to create the progressbar object outside the loop

pb = txtProgressBar(min = 0, max = length(ind), initial = 0) 

then inside you need to update with every iteration

setTxtProgressBar(pb,stepi)

or

setTxtProgressBar(pb,i)

Remember to close the progress bar to output the newline character. From the documentation:

The progress bar should be closed when finished with: this outputs the
final newline character.

Simply add at the end of your loop:

close(pb)

This will work poorly if the loop also has print commands in it



Related Topics



Leave a reply



Submit