R sink(): Error, cannot split the message connection

好久不见. 提交于 2021-02-19 02:59:06

问题


I am trying to log the errors and warnings of an R script into an external file. At the same time I want to be able to see the errors and warnings in the console in RStudio (useful to develop and debug). I am trying to use the following code:

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

But when I try to split the message connection using the funciton sink() I get the following error:

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

Is there any workaround or alternative solution?

Thanks


回答1:


So, I tried using split = T in sink.

But, it's not doing what we want it to do. It's either redirecting output to log file or throwing an error which you pointed and is not printing errors or warning messages to RStudio console.

There's a work around to your problem which might solve your problem.

I tried using this:-

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

It gave an output to console:-

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

So, the above piece of code diverted the error and warning message to log file and printed it in console too.

You can use sink normally and then use readLines to print your error and warning messages to console.



来源:https://stackoverflow.com/questions/48010243/r-sink-error-cannot-split-the-message-connection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!