2017-06-23 72 views
1

我在R中写了一个函数来打印任何消息都记录文件和控制台。但是,如果在运行代码时出现任何意外错误,则仅向控制台显示错误。有没有办法将错误消息写入控制台和日志文件?下面是函数..错误处理和登录R

log_con <- file("Text1.txt", open="a") 

loggerfn<-function(Message,LogConnection=log_con){ 
    cat(Message, file = LogConnection) 
    cat(Message) 
} 

下面是示例代码...

for (i in 1:10) 
{ 
    loggerfn("loop begins\n",log_con) 
    a <- rnorm(n = 100, mean = i, sd = 5) 
    loggerfn(mean(a),log_con) 
    loggerfn("loop Completed\n",log_con) 
    if(i==8){ 
    sdfs 
    } 
} 

在上面的代码我特意通过提供未定义的对象sdfd.Below提供错误消息引入的误差仅示出在控制台中,有没有办法将错误消息写入控制台和日志文件?

Error: object 'sdfs' not found 
+0

你听说过在R中使用try-catch块吗? –

+0

是的..我正在处理一些重大项目。我无法预测错误使用try,catch块在每个模块中。 – PPC

回答

1

使用sink()将消息以及警告转移到文件。关键是要设置的参数类型=“消息”

参阅http://www.statmethods.net/interface/io.htmlOutput error/warning log (txt file) when running R script under command line https://stat.ethz.ch/R-manual/R-devel/library/base/html/sink.html

sink()的函数定义了输出的方向。

描述

水槽转移R输出到连接(并停止这种转移)。

sink.number() 

报告有多少转移正在使用中。

sink.number(type = "message")报告当前正用于错误消息的连接的编号。 用法

sink(file = NULL, append = FALSE, type = c("output", "message"), 
    split = FALSE) 

sink.number(type = c("output", "message")) 

直接输出到一个文件

sink("myfile", append=FALSE, split=FALSE) 

返回输出到终端

sink() 

追加选项控制输出是否会覆盖或添加到文件中。分割选项决定输出是否也发送到屏幕以及输出文件。

下面是一些sink()函数的例子。

输出指向c:\ projects目录中的output.txt。 输出会覆盖现有文件。没有输出到终端。

sink("c:/projects/output.txt") 

输出指向myfile.txt在cwd。输出附加到现有文件 。输出也发送到终端。

sink("myfile.txt", append=TRUE, split=TRUE) 

重定向输出时,使用cat()函数来标注输出。

+1

我已经尝试了下面的代码,它没有写入错误消息(_Error:object'sdfs'not found_)来记录文件。你能检查一下吗? (“我在1:10”) cat(“循环开始\”)(sink)(“myfile.txt”,append = TRUE,split = TRUE) sink.number(type = c(“output” (平均(a)) cat(“loop已完成\ n”) if(i == 8){sdfs} 如果(i == 8){sdfs} a < - rnorm(n = 100,mean = i,sd = 5) } sink()' – PPC