capture strings that cannot be converted to date in R

Tag: r , error-handling Author: yunxin312 Date: 2012-04-06

I want to create an if statement if the string cannot be converted to date, like the one below:

as.Date("2010-00-01")

But running the line above just keep giving the error output below:

Error in charToDate(x) : 
  character string is not in a standard unambiguous format

Which I cannot use it for if statement, how can I use a if statement if the string cannot be converted to date? Thanks.

Best Answer

Provide the format arg so it won't be ambiguous. Bad dates are then always turned into NA.

d <- as.Date("2010-01-31", format="%Y-%m-%d") # OK
is.na(d) # FALSE

d <- as.Date("2010-00-31", format="%Y-%m-%d") # NA
is.na(d) # TRUE

comments:

I prefer Tommy's answer, as it is done without creating new function, but learning tryCatch from kohske is also good.

Other Answer1

Here is a quick definition:

isDatable <- function(x) tryCatch(as.Date(x), error = function(e) FALSE)

Then,

> isDatable("2012-00-01")
[1] FALSE
> isDatable("2012-01-01")
[1] "2012-01-01"

so you can use with if:

if (!isDatable("2012-00-01")) {
    # something 
}