【问题标题】:How do you print to stderr in R?你如何在 R 中打印到标准错误?
【发布时间】:2010-11-09 16:33:15
【问题描述】:

如何在R 中打印到stderr

这对于用Rscript 编写的脚本特别有用。

【问题讨论】:

    标签: r printing stderr


    【解决方案1】:

    实际上以下对我有用:

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

    【讨论】:

    • 这是在 Linux 上,使用 R 2.8.1(使用 Rscript)
    • 此代码也适用于 Windows。如需更多格式控制,可以使用 cat 代替 write。
    • FWIW,这是有限的,因为它只有在第一个参数可以由 cat 输出时才有效。正如 Galwegian 所说,有些课程需要 print 才能工作,而您必须使用 sink
    【解决方案2】:

    这是用于在 Rscript 中调试/详细使用的更灵活的版本。它不仅会按照您的要求打印到 stderr,而且还允许您传递可变数量的参数、类型等,就像 printf 所做的那样。

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

    现在可以做如下事情:

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

    等等

    【讨论】:

    【解决方案3】:
    message('for writing diagnostic info to standard error')
    

    message 用于生成“简单”的诊断消息,这些消息既不是警告也不是错误,但仍表示为条件。与警告和错误不同,最后的换行符被视为消息的一部分,并且是可选的。默认处理程序将消息发送到 stderr() 连接。

    【讨论】:

    • 对我来说似乎是最好的解决方案
    【解决方案4】:

    是否可以配置打印 打印到 stderr 的函数?

    From Ripley himself:

    不,但标准输出的位置是 由 sink() 控制,所以你可以 达到同样的效果。 R 内部 不知道输出来自哪里 print() (这不仅仅是一个 功能,但数百种方法)。

    【讨论】:

      【解决方案5】:

      与接受的答案建议使用write() 函数相反,这将是对该函数的不当使用,因为它旨在用于将数据写入 到文件而不是消息。从write() documentation,我们有:

      数据(通常是矩阵)x 被写入文件file。如果 x 是二维矩阵,则需要对其进行转置以使文件中的列与内部表示中的列相同。

      此外,请注意write() 为列的data 输出提供了便利的包装器。

      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)
      

      也就是说,我建议在 file = ... 参数中使用 cat() 和适当的 condition handler stderr() or stdout()

      因此,要将消息写入标准错误,应使用:

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

      或者:

      message("also sent to standard error")
      

      对于标准out,直接使用cat(),因为它默认设置为写入stdout()

      cat("displays in standard out by default")
      

      【讨论】:

      • 我不明白使用自己的文件描述符写入:stdoutstdinstderrare handled like any other file (at least in *nix systems) 的问题。
      • R 中的write() 函数是一个方便的包装器,用于将统一格式的数据输出到文件。在编写文本时——比如状态更新——message() 更适合该任务,因为它被预先配置为写入stderr()。同样,cat() 擅长写信给stdout()
      猜你喜欢
      • 2017-11-12
      • 2023-04-06
      • 1970-01-01
      • 2013-12-07
      • 1970-01-01
      • 2018-11-25
      • 1970-01-01
      • 1970-01-01
      • 2012-09-02
      相关资源
      最近更新 更多