为什么 message()比 R 中的 print()更适合写包?

我希望知道为什么在打印诊断信息时,message()print()更好。

例如,print()函数是打印 R 对象(如 'iris')的更好选择,而当我们想要连接字符串(如 message("a", "b")print(paste0("a", "b"))短)时,message()更好。

然而,我认为有更多的差异比上面列出的那些简单的。我已经阅读了这两种方法的文档

但是,它们似乎没有我希望我的问题所提供的信息。

如果有人告诉我们在哪种情况下 message()优于 print(),以及为什么,我将不胜感激。

45508 次浏览

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 (cat()0, cat()1, and cat()2) send their output to stderr or the standard error. That is, the cat()3 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 cat()4 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(), sink()0, sink()1, 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 sink()2, sink()3, or sink()4.

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