Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

I hope to know why message() is a better choice than print() when it comes to printing diagnostic messages.

For example, the print() function is a better choice to print R object such as 'iris', whereas, message() is better when we want to concatenate strings e.g. message("a", "b") is shorter than print(paste0("a", "b")).

However, I think there are more differences than those simple ones listed above. I have read the documentation for both methods

  • http://stat.ethz.ch/R-manual/R-devel/library/base/html/message.html,
  • http://stat.ethz.ch/R-manual/R-devel/library/base/html/print.html

but, it seems they are not as informative as I had hoped to my question.

I would appreciate if someone let us know in which case message() is better than print(), and why.

like image 214
Kim Avatar asked Apr 18 '16 16:04

Kim


People also ask

How cat () is different from print () in R?

The simple printing method in R is to use print() . As its name indicates, this method prints its arguments on the R console. However, cat() does the same thing but is valid only for atomic types (logical, integer, real, complex, character) and names, which will be covered in the later chapters.

What is the difference between print and print paste in R?

paste0 () — this function concatenates the input values in a single character string. The difference between: paste and paste0 is that paste function provides a separator operator, whereas paste0 does not. print ()- Print function is used for printing the output of any object in R.

What does the print function do in R?

The print() is a built-in R function that prints its argument. The print() function accepts three arguments and does not return any value. Instead, the print() method will print out the argument on the screen.

How do I print a message in R?

To display ( or print) a text with R, use either the R-command cat() or print(). Note that in each case, the text is considered by R as a script, so it should be in quotes. Note there is subtle difference between the two commands so type on your prompt help(cat) and help(print) to see the difference.


1 Answers

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

like image 95
coatless Avatar answered Oct 10 '22 04:10

coatless