How to Print to Stderr in R

How do you print to stderr in R?

Actually the following works for me:

write("prints to stderr", stderr())

write("prints to stdout", stdout())

How to print an R object to stderr in Rcpp?

At the moment, it seems that this hack is the only way to go. It's not very efficient, as we go back from C++ to R to get the value as a nice string.

library(Rcpp)

sourceCpp(code='

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
void test(SEXP key, Function generate_error) {
std::string s = as<std::string>(generate_error(key));
stop(s);
}

/*** R

generate_error <- function(key) {
paste("Key not found:", capture.output(print(key)))
}

try( test("x", generate_error) )
try( test(c(1,2,3), generate_error) )
*/

')

send R diagnostic messages to stdout instead stderr

While this is very likely not a best practice, you could override message with a version that writes to stdout() by default, right?

message <- function (..., domain = NULL, appendLF = TRUE) 
{
args <- list(...)
cond <- if (length(args) == 1L && inherits(args[[1L]], "condition")) {
if (nargs() > 1L)
warning("additional arguments ignored in message()")
args[[1L]]
}
else {
msg <- .makeMessage(..., domain = domain, appendLF = appendLF)
call <- sys.call()
simpleMessage(msg, call)
}
defaultHandler <- function(c) {
cat(conditionMessage(c), file = stdout(), sep = "")
}
withRestarts({
signalCondition(cond)
defaultHandler(cond)
}, muffleMessage = function() NULL)
invisible()
}

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

How I can print to stderr in C?

The syntax is almost the same as printf. With printf you give the string format and its contents ie:

printf("my %s has %d chars\n", "string format", 30);

With fprintf it is the same, except now you are also specifying the place to print to:

FILE *myFile;
...
fprintf( myFile, "my %s has %d chars\n", "string format", 30);

Or in your case:

fprintf( stderr, "my %s has %d chars\n", "string format", 30);

How to append stderr and stdout output to file in system2 R command?

And this one is even better since it permits the use of more modern system command and permits doing clearer logging.

result <- system2(command="ls", 
args=c("-l", "/etc/"),
stdout="/tmp/stdout.log",
stderr="/tmp/stderr.log",
wait=TRUE)
now <- date()
cat(paste0("Executed: ", now, "\n"), file="/tmp/stdoutmain.log", append=TRUE)
file.append("/tmp/stdoutmain.log", "/tmp/stdout.log")
cat(paste0("Executed: ", now, "\n"), file="/tmp/stderrmain.log", append=TRUE)
file.append("/tmp/stderrmain.log", "/tmp/stderr.log")

How can I redirect R warning messages to STDOUT?

Look at the help page for sink():

‘sink’ diverts R output to a connection. If ‘file’ is a character
string, a file connection with that name will be established for
the duration of the diversion.

Normal R output (to connection ‘stdout’) is diverted by the
default ‘type = "output"’. Only prompts and (most) messages
continue to appear on the console. Messages sent to ‘stderr()’
(including those from ‘message’, ‘warning’ and ‘stop’) can be
diverted by ‘sink(type = "message")’ (see below).



Related Topics



Leave a reply



Submit