Careful with tryCatch

[This article was first published on Econometrics and Free Software, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

tryCatch is one of the functions that allows the users to handle errors in a simple way. With it, you can do things like: if(error), then(do this).

Take the following example:

Error in sqrt("a") : non-numeric argument to mathematical function

Now maybe you’d want something to happen when such an error happens. You can achieve that with tryCatch:

tryCatch(sqrt("a"), error=function(e) print("You can't take the square root of a character, silly!"))
## [1] "You can't take the square root of a character, silly!"

Why am I interested in tryCatch?

I am currently working with dates, specifically birthdays of people in my data sets. For a given mother, the birthday of her child is given in three distinct columns: a column for the child’s birth year, birth month and birth day respectively. I’ve wanted to put everything in a single column and convert the birthday to unix time (I have a very good reason to do that, but I won’t bore you with the details).

Let’s create some data:

mother <-, day=1, year=1988))

In my data, there’s a lot more columns of course, such as the mother’s wage, education level, etc, but for illustration purposes, this is all that’s needed.

Now, to create this birthday column:

mother$birth1 <- as.POSIXct(paste0(as.character(mother$year), 
                                   "-", as.character(mother$month), 
                                   "-", as.character(mother$day)), 

and to convert it to unix time:

mother$birth1 <- as.numeric(as.POSIXct(paste0(as.character(mother$year), 
                                              "-", as.character(mother$month), 
                                              "-", as.character(mother$day)),

##   month day year    birth1
## 1    12   1 1988 596934000

Now let’s see what happens in this other example here:

mother2 <-, day=30, year=1988))

mother2$birth1 <- as.POSIXct(paste0(as.character(mother2$year), 
                                    "-", as.character(mother2$month), 
                                    "-", as.character(mother2$day)), 

This is what happens:

Error in as.POSIXlt.character(x, tz, ...) : 
  character string is not in a standard unambiguous format

This error is to be expected; there is no 30th of February! It turns out that in some rare cases, weird dates like this exist in my data. Probably some encoding errors. Not a problem I thought, I could use tryCatch and return NA in the case of an error.

mother2 <-, day=30, year=1988))

mother2$birth1 <- tryCatch(as.POSIXct(paste0(as.character(mother2$year), 
                                    "-", as.character(mother2$month), 
                                    "-", as.character(mother2$day)), 
                             origin="1970-01-01"), error=function(e) NA)

##   month day year birth1
## 1     2  30 1988     NA

Pretty great, right? Well, no. Take a look at what happens in this case:

mother <-, 2), day=c(1, 30), year=c(1988, 1987)))
##   month day year
## 1    12   1 1988
## 2     2  30 1987

We’d expect to have a correct date for the first mother and an NA for the second. However, this is what happens

mother$birth1 <- tryCatch(as.POSIXct(paste0(as.character(mother$year), 
                                    "-", as.character(mother$month), 
                                    "-", as.character(mother$day)), 
                             origin="1970-01-01"), error=function(e) NA)

##   month day year birth1
## 1    12   1 1988     NA
## 2     2  30 1987     NA

As you can see, we now have an NA for both mothers! That’s actually to be expected. Indeed, this little example illustrates it well:

sqrt(c(4, 9, "haha"))
Error in sqrt(c(4, 9, "haha")) : 
  non-numeric argument to mathematical function

But you’d like to have this:

[1]  2  3 NA

So you could make the same mistake as myself and use tryCatch:

tryCatch(sqrt(c(4, 9, "haha")), error=function(e) NA)
## [1] NA

But you only get NA in return. That’s actually completely normal, but it took me off-guard and I spent quite some time to figure out what was happening. Especially because I had written unit tests to test my function create_birthdays() that was doing the above computations and all tests were passing! The problem was that in my tests, I only had a single individual, so for a wrong date, having NA for this individual was expected behaviour. But in a panel, only some individuals have a weird date like the 30th of February, but because of those, the whole column was filled with NA’s! What I’m doing now is trying to either remove these weird birthdays (there are mothers whose children were born on the 99-99-9999. Documentation is lacking, but this probably means missing value), or tyring to figure out how to only get NA’s for the “weird” dates. I guess that the answer lies with dplyr’s group_by() and mutate() to compute this birthdays for each individual separately.

To leave a comment for the author, please follow the link and comment on their blog: Econometrics and Free Software. offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)