Using tryCatch function of R in a loop

后端 未结 1 1280
没有蜡笔的小新
没有蜡笔的小新 2021-01-20 14:47

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

1条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-20 15:24

    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

    0 讨论(0)
提交回复
热议问题