I'm working on a loop, and I want to extract the index causing an error in R and put it into a separate object.
Here is an example modified from an answer in a stack overflow post. It skips and reports the nature of the error.
for (i in 1:15) {
tryCatch({
print(i)
if (i==7) stop("Urgh, the iphone is in the blender !")
if (i==9) stop("Urgh, the iphone is in the blender !")
if (i==14) stop("Urgh, the iphone is in the blender !")
}, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}
In addition to skipping and reporting the error, how can I improve this code to create a separate object with the index causing the error? Such that, it creates an object, Index Error
, with 7, 9, and 14 inside it.
Thank You!