I'm trying to write the summary of each for loop execution and wish to write the error in the for loop, in case if any, into the data frame and append the summary (data frame temp_log in code below) to text file TextLogFile.txt for each of i values (i 1 to 5).
To give more clarity please see the two examples below.
Example-1:
In below example-1 code does not throw any error, I wish if I can assign variable 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)
}
# Example-2
In below example-2 for i=3 code throws the error
Error in tp0 : object 'tp0' not found
Now I want variable Error to be 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)
}
Ideal output I expect would be something like below.
"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"
I read about try, tryCatch, few related questions on handling errors in R but could not implement it the way I really wanted. Is there a way I can do this implementation?
I'm in the middle of learning and implementing R, any help on this would be highly appreciated.