[R] as.Date() behaviour when incomplete input string

Nicolas Prune np at alambic.org
Fri Feb 9 12:21:10 CET 2007


Dear all,

I would like to know the month on a string formatted as "2004-01", using as.Date
(not just stripping the string !)

?as.Date says that in case of an incomplete input string, the answer is
system-specific.
The following has been tested on  R 2.4.1, on Ubuntu Linux and WinXP.

> mydate <- "2004-01"
> as.Date(mydate)
Error in fromchar(x) : character string is not in a standard unambiguous format.
(I understand that).
> as.Date(mydate,format="%Y-%m")
NA (is there still ambiguity in my format ??)

Investigating a bit, I found a strange behaviour in :

> as.Date("2004-01-12",format="%Y-%m-%d")
"2005-01-12"

> as.Date("2004-01",format="%Y-%m")
NA (why can't R see anything ?)

> as.Date("2004",format="%Y")
"2005-02-09" (month and day are replaced by today's values, normal behaviour).

Why can't R see the month, but see the year ?

For the moment, I do this ugly thing :

> mydate <- paste(mydate,"-01",sep="") in order send an unambiguous string to
as.Date.

Any idea how I can do better ?

Thanks and regards,

Nicolas Prune



More information about the R-help mailing list