21

如果我在命令行下运行 R 脚本(实际上是通过在 VBA 中调用来运行它),我如何将任何错误/警告消息输出到 txt 文件?

4

2 回答 2

39

您可以使用sink()将消息和警告转移到文件中。诀窍是设置参数type="message"

这是一个改编自帮助的示例?sink

setwd(tempdir())

## capture messages and errors to a file.
zz <- file("all.Rout", open="wt")
sink(zz, type="message")

try(log("a"))

## reset message sink and close the file connection
sink(type="message")
close(zz)

## Display the log file
readLines("all.Rout")
[1] "Error in log(\"a\") : Non-numeric argument to mathematical function"
于 2012-07-26T10:11:29.733 回答
21

要关闭与日志文件的连接,您必须使用sink(type="message")而不是sink()then close(zz)

于 2014-06-24T16:22:02.960 回答