How do you print to stderr in R?

前端 未结 5 1686
有刺的猬
有刺的猬 2020-12-03 02:26

How do you print to stderr in R?

This would especially useful for scripts written in Rscript.

相关标签:
5条回答
  • 2020-12-03 02:54

    Actually the following works for me:

    write("prints to stderr", stderr())
    
    write("prints to stdout", stdout())
    
    0 讨论(0)
  • 2020-12-03 02:59
    message('for writing diagnostic info to standard error')
    

    message is used for generating ‘simple’ diagnostic messages which are neither warnings nor errors, but nevertheless represented as conditions. Unlike warnings and errors, a final newline is regarded as part of the message, and is optional. The default handler sends the message to the stderr() connection.

    0 讨论(0)
  • 2020-12-03 03:00

    Contrary to the accepted answer's suggestion to use the write() function, this would be an inappropriate use of the function as it is designed to be used for writing data to a file instead of messages. From the write() documentation, we have:

    The data (usually a matrix) x are written to file file. If x is a two-dimensional matrix you need to transpose it to get the columns in file the same as those in the internal representation.

    Moreover, note that write() provides a convenience wrapper for data output of columns.

    write
    # function (x, file = "data", ncolumns = if (is.character(x)) 1 else 5, 
    #     append = FALSE, sep = " ") 
    # cat(x, file = file, sep = c(rep.int(sep, ncolumns - 1), "\n"), 
    #     append = append)
    

    That said, I would recommend using cat() alongside of the appropriate condition handler stderr() or stdout() in file = ... parameter.

    Thus, to write a message to standard error, one should use:

    cat("a message that goes to standard error", file = stderr())
    

    Or:

    message("also sent to standard error")
    

    For standard out, just use cat() directly as it is setup to write to stdout() by default.

    cat("displays in standard out by default")
    
    0 讨论(0)
  • 2020-12-03 03:14

    Is it possible to configure the print function to print to stderr?

    From Ripley himself:

    No, but where standard output goes is controlled by sink(), so you can achieve the same effect. R internally has no idea what output comes from print() (which is not just one function but hundreds of methods).

    0 讨论(0)
  • 2020-12-03 03:18

    Here's a more flexible version for debugging/verbose use in Rscript. Not only it prints to stderr as you ask, but it also allows you to pass variable number of arguments, types etc, like printf does.

    v <- function(...) cat(sprintf(...), sep='', file=stderr())
    

    Now one can do things like:

    v("name: %s  age: %d\n", name, age)
    

    etc.

    0 讨论(0)
提交回复
热议问题