5

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?

1
  • If you have at least one character element in a vector, all the elements becomes character. Instead you may need a list Commented Apr 22, 2018 at 13:45

1 Answer 1

4

The reason is a that one of the elements in the vector is character and a vector cannot have mixed types. So, it is coerced to character. Instead we should have a list where each element can have different types

x <- list(1,2,"a" , 4)

Now, running the OP' code gives

for (i in x) {
   y <- tryCatch(print(sqrt(i)) , error= function(e) {return(0)}  )
   if (y==0) {print("NOT POSSIBLE")
              next}
 }
#[1] 1
#[1] 1.414214
#[1] "NOT POSSIBLE"
#[1] 2

If we can use only a vector, then there should be a provision to convert it to numeric within the loop, but it would also return an NA for the third element as

as.numeric('a')
#[1] NA

Warning message: NAs introduced by coercion

and ends the for loop

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.