r - R 中的消息函数不写入文本文件/将消息打印到标准输出

标签 r console sink

我正在使用 print()、cat() 和 message() 函数向 R 控制台写入一些文本。我希望将控制台输出收集到一个文本文件中,因此我将代码夹在一对 sink() 函数之间。最终代码如下:

sink("output_filename.txt") 
print("some text with print function")
cat("some text with cat function")
message("some text with message function")
sink()

当我运行此代码时, print 和 cat 按预期工作,而消息的输出写入控制台而不是输出文本文件。为什么会发生这种情况以及如何解决这个问题?我不喜欢用替代品来取代消息功能。

最佳答案

喜欢jogo评论中已经提到,message() 发送到 stdeer,而不是 stdout。您可以使用 sink(stdout(), type = "message")

更改此设置
sink("output_filename.txt") 
sink(stdout(), type = "message")
print("some text with print function")
cat("some text with cat function\n")
message("some text with message function")
sink()

来自documentary sink()的:

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).

您也可以在完成后将其更改回来,因为警告和停止也会以这种方式更改为stdout

关于r - R 中的消息函数不写入文本文件/将消息打印到标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56607627/

相关文章:

file - GNU radio 文件接收器如何工作?

dart - 在 Dart 中使用 Sink 和 Pipe 与 Streams 有什么区别?

使用 R 中的 sink 和 sprintf 输出删除 [1]

r - 将多属性栅格中的栅格属性用于 R 中绘图中的颜色级别

R 选择组中的第二个元素

ruby-on-rails - 如何在脚本/控制台中禁用记录器

eclipse - 为什么我的 Java 程序通过 Eclipse 运行的速度比通过 shell 运行的速度快 4 倍?

javascript - `await` 慢于 Chrome 中应有的速度

r - h2oensemble 值错误[[3L]](cond) : argument "training_frame" must be a valid H2O H2OFrame or id

r - 为什么 R data.table 将列添加到我没有引用的另一个数据表中?