I want to use tryCatch function in a loop which sometimes works but sometimes it does not, and I do not know where does it have errors to solve the problem and create a loop which always works. So I want it just to neglect the error and go to next round. To simplify the problem, for example, I have this x, and I want to have sqrt of each value. I write:
x <- c(1, 2, "a", 4)
for (i in x) {
y <- tryCatch(print(sqrt(i)) , error = function(e) { return(0) } )
if (y==0) {
print("NOT POSSIBLE")
next
}
}
I suppose this code should give me this answer:
[1] 1
[1] 1.414214
[1] "NOT POSSIBLE"
[1] 2
but it gives me this:
[1] "NOT POSSIBLE"
[1] "NOT POSSIBLE"
[1] "NOT POSSIBLE"
[1] "NOT POSSIBLE"
I could not find anywhere explaining that why this happens. Why this function does not apply to each round of the loop separately and what can I do about it?
list