我正在尝试编写每个for循环执行的摘要,并希望将for循环中的错误(如果有的话)写入数据框,并将摘要(以下代码中的数据框temp_log)附加到文本每个i值(i 1到5)的文件TextLogFile.txt。
为更加清楚起见,请参见下面的两个示例。
示例1:
在下面的example-1代码中,不会抛出任何错误,我希望是否可以分配变量Error <- "No Error"
LogFile <- paste(paste("TestLogFile", Sys.Date(), sep = "_"), "txt", sep=".")
for(i in 1:5){
Run <- i
ID <- i + 100
TimeStamp <- format(Sys.time(), tz="EST")
Runtime <- 1
#### Assign Error <- "No Error" in case no error in loop ###########################
#### Assign Error <- Actual error in case of error in loop ###########################
# Error <- "No Error"
temp_log <- cbind.data.frame(Run, ID, TimeStamp, Runtime, Error)
write.table(temp_log, LogFile, col.names = T, row.names = F, append = T)
}
#示例2
在下面的示例2中,i = 3的代码抛出错误
Error in tp0 : object 'tp0' not found
现在我希望变量Error为Error <- "Error in tp0 : object 'tp0' not found"
LogFile <- paste(paste("TestLogFile", Sys.Date(), sep = "_"), "txt", sep=".")
for(i in 1:5){
Run <- i
ID <- i + 100
TimeStamp <- format(Sys.time(), tz="EST")
Runtime <- 1
if(i == 3){
tp <- Runtime + tp0
}
#### Assign Error <- "No Error" in case no error in loop ###########################
#### Assign Error <- Actual error in case of error in loop ###########################
# Error <- "Error in tp0 : object 'tp0' not found"
temp_log <- cbind.data.frame(Run, ID, TimeStamp, Runtime, Error)
write.table(temp_log, LogFile, col.names = T, row.names = F, append = T)
}
我希望理想的输出如下所示。
"Run" "ID" "TimeStamp" "Runtime" "Error"
1 101 "2019-12-09 07:45:25" 1 "No Error"
"Run" "ID" "TimeStamp" "Runtime" "Error"
2 102 "2019-12-09 07:45:25" 1 "No Error"
"Run" "ID" "TimeStamp" "Runtime" "Error"
3 102 "2019-12-09 07:45:25" 1 "Error: object 'tp0' not found"
"Run" "ID" "TimeStamp" "Runtime" "Error"
4 102 "2019-12-09 07:45:25" 1 "No Error"
"Run" "ID" "TimeStamp" "Runtime" "Error"
5 102 "2019-12-09 07:45:25" 1 "No Error"
我阅读了有关try,tryCatch的信息,以及一些有关处理R中错误的相关问题,但无法按照我真正想要的方式实现。有什么办法可以实现呢?
我正在学习和实现R的过程中,在此方面的任何帮助将不胜感激。
答案 0 :(得分:1)
您可以尝试执行以下操作:
for(i in 1:5) {
Error = "No Error"
tryCatch({
Run <- i
ID <- i + 100
TimeStamp <- format(Sys.time(), tz = "EST")
Runtime <- 1
if (i == 3) {
tp <- Runtime + tp0
}
}, error = function(e) {
Error <<- e$message
})
temp_log <- cbind.data.frame(Run, ID, TimeStamp, Runtime, Error)
print(temp_log)
}
这将打印:
Run ID TimeStamp Runtime Error
1 1 101 2019-12-09 14:52:54 1 No Error
Run ID TimeStamp Runtime Error
1 2 102 2019-12-09 14:52:54 1 No Error
Run ID TimeStamp Runtime Error
1 3 103 2019-12-09 14:52:54 1 object 'tp0' not found
Run ID TimeStamp Runtime Error
1 4 104 2019-12-09 14:52:54 1 No Error
Run ID TimeStamp Runtime Error
1 5 105 2019-12-09 14:52:54 1 No Error
祝你好运!