R sink():错误,无法拆分消息连接



我正在尝试将R脚本的错误和警告记录到外部文件中。同时,我希望能够在RStudio的控制台中看到错误和警告(对开发和调试很有用(。我正在尝试使用以下代码:

logfile <- file("my_file_path", open="wt")
sink(logfile, type="message", split = TRUE)

但是当我尝试使用 funciton sink(( 拆分消息连接时,出现以下错误:

Error in sink(logfile, type = "message", split = TRUE) : 
  cannot split the message connection

是否有任何解决方法或替代解决方案?

谢谢

所以,我尝试在sink中使用split = T

但是,它没有做我们想让它做的事情。它要么将输出重定向到日志文件,要么抛出您指出的错误,并且不会将错误或警告消息打印到 RStudio 控制台。

有一个解决方法可以解决您的问题。

我尝试使用这个:-

# path to your log file
file_path <- "path/documents/log/log.txt"
# open a connection to your log file
file_con <- file(file_path, open = "a")
## capture warning messages and errors to log file
sink(file_con, type = "message")
## to get error and warning message 
sum(a)
warning("this is a warning message. please ignore")
## revert output back to the console and close the file connection
sink(type = "message")
close(file_con)
# get all the errors and warnings from log file
readLines(file_path)

它向控制台提供了输出:-

[1] "Error: object 'a' not found"              
[2] "Warning message:"                         
[3] "this is a warning message. please ignore "

因此,上面的代码段将错误和警告消息转移到日志文件中,并将其打印在控制台中。

您可以正常使用sink,然后使用 readLines 将错误和警告消息打印到控制台。

最新更新