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)