Error Handling in For Loop

Greetings all,

I have a for loop that cycles through a number of records stored in a dataframe and attempts to clean the data.
However, on occasion a record will generate an error due to bad data and will then kill the full process.
Is it possible to set up the loop so that it will advance to the next value in the loop?

example...
if the for loop is set to run through thirty rows of data
and row 23 triggers a critical error, can i set the loop up so that it will disregard row 23 and move on to row 24?

I've been reading on tryCatch but am having problems on finding good documenation on how to use it.

Jarrod

tryCatch is indeed one such way to handle errors in a loop.
purrr is another way to do the same:

library(magrittr)
safe_log <- purrr::possibly(log, otherwise = 0)

list(2, 10, "34", 15) %>%
  purrr::map(safe_log)
#> [[1]]
#> [1] 0.6931472
#> 
#> [[2]]
#> [1] 2.302585
#> 
#> [[3]]
#> [1] 0
#> 
#> [[4]]
#> [1] 2.70805

Created on 2018-12-28 by the reprex package (v0.2.1)

As you can see, "34" would have thrown an error and you wouldn't get any result back. But since log is wrapped into purrr::possibly, it doesn't throw an error anymore.

4 Likes

About documentation on tryCatch, I would advice advanced R book.
First version:
http://adv-r.had.co.nz/Exceptions-Debugging.html
and very new version still in progress and unpublished yet
https://adv-r.hadley.nz/conditions.html

3 Likes

Thank You! I will look into this today.

Always grateful for the help and advice!

Jarrod

1 Like

Thank you! This has been on my reading list for sometime. I'm going to bump it to the top for certain.

Jarrod

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