RockScience
RockScience

Reputation: 18610

return NA when the date is not correct

I am trying to convert a string date to a POSIXct using the R command as.POSIXct If one of the date in the list is incorrect (31st of Feb here), it returns an error. How can I get an NA instead?

I read in the help that Date-times known to be invalid will be returned as NA. Is this a bug?

as.POSIXct(c("2011-02-02", "2011-02-31"), tz="GMT")

Upvotes: 2

Views: 1222

Answers (1)

Timo
Timo

Reputation: 5390

You should also provide the format string to the function, like this:

> as.POSIXct(c("2011-02-02", "2011-02-31"), tz="GMT", format='%Y-%m-%d')
[1] "2011-02-02 GMT" NA 

The problem is that without format string the function cannot figure out, which part of the string represents the month and which part the day.

EDIT:

This is actually what the error complained about:

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

Upvotes: 8

Related Questions