skipping an error to continue iterations

Hi
I am trying to run a large chunk of code inside for loop and store the output in matrices. There is an error message for certain samples and I want to skip the iterations with error message and move to next iteration. Can anyone please explain, how can I do that.

The functions try() and tryCatch() could help you do this. Here are some very simple examples of processing data in a list where one element causes an error. In the first version, the fourth element does not get calculated due to the error. Using try or tryCatch, the error can be handled and the loop proceeds to the fourth element.

DATA <- list(13, 23, "A", 100)
OUT <- list(NA, NA, NA, NA)
for (i in 1:4) {
  OUT[i] <- log(DATA[[i]])
}
#> Error in log(DATA[[i]]): non-numeric argument to mathematical function
OUT
#> [[1]]
#> [1] 2.564949
#> 
#> [[2]]
#> [1] 3.135494
#> 
#> [[3]]
#> [1] NA
#> 
#> [[4]]
#> [1] NA
OUT2 <- list(NA, NA, NA, NA)
for (i in 1:4) {
  OUT2[i] <- try({
    log(DATA[[i]])
  }, 
  silent = TRUE)
}
OUT2
#> [[1]]
#> [1] 2.564949
#> 
#> [[2]]
#> [1] 3.135494
#> 
#> [[3]]
#> [1] "Error in log(DATA[[i]]) : non-numeric argument to mathematical function\n"
#> 
#> [[4]]
#> [1] 4.60517

#tryCatch
OUT3 <- list(NA, NA, NA, NA)

for (i in 1:4) {
  OUT3[i] <- tryCatch({
    log(DATA[[i]])
  }, error = function(e) -999)
} 
OUT3
#> [[1]]
#> [1] 2.564949
#> 
#> [[2]]
#> [1] 3.135494
#> 
#> [[3]]
#> [1] -999
#> 
#> [[4]]
#> [1] 4.60517


Created on 2021-09-09 by the reprex package (v0.3.0)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.