[R] Error as.Date on Invalid Dates

Brian D Ripley ripley at stats.ox.ac.uk
Thu Jan 22 14:45:21 CET 2009


On Thu, 22 Jan 2009, Terry Therneau wrote:

> -----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.

So does as.Date *if you specify the format* (as you have to with your 
as.date: it has a default one):

> as.Date(date1, format="%Y-%m-%d")
[1] NA


>
>> 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).


-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list