我正在使用 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/