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
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 type
s
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