[R] Error as.Date on Invalid Dates

Terry Therneau therneau at mayo.edu
Thu Jan 22 14:36:27 CET 2009


-----begin included message --------
However, as.Date encounters an error when the string does not represent an
actual date.
eg:
 > date1 <- "2009-02-29"  # Note: 2009 not a leap year
> as.Date(date1)
Error in fromchar(x) :
  character string is not in a standard unambiguous format

As I have many instances of date entries like this, date1, date2, date3,
etc. , I'd like the script to error out gracefully and to be able to point
the user to which date they need to correct, rather than "Error in
fromchar(x)...", which doesn't make it obvious what they need to do to fix
the error.

Ideally I'd love to send the user a message like:
print(paste(date1, "is an invalid date.  Refer to calendar.", sep=" "))

If anyone has any suggestions on catching this type of error and feedback
which directs the user, it would be much appreciated.

------- end inclusion ---------

One idea is to use the as.date function, for the older (and less capable) 'date' 
class.  This is currently loaded by default with library(survival).  It returns 
NA for an invalid date rather than dying.  

> as.date(c("2009-5-10", "2007/2/29", "1953/3/10"), order='ymd')
[1] 10May2009 NA        10Mar53  

The order argument in needed here since the default assumption is the US habit 
of month-day-year.

You can then convert to the more modern format.

> temp <- as.date(c("2009-5-10", "2007/2/29", "1953/3/10"), order='ymd')
> as.Date(temp)
[1] "2009-05-10" NA           "1953-03-10"

  	Terry Therneau
  	

Note: as.Date will return a string with NA's as well, AS LONG AS the first date 
in the sequence is legal.  It uses the first to pick a format (I presume).




More information about the R-help mailing list