Order Dependence in as.Date

I was working on a task a few days ago that required converting a lot of timestamps into dates (not times, just dates). Thankfully, as.Date seemed to be working fine as a default approach, but then an error showed up:

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

Fair enough, nobody expects to get through parsing dates without a few hangups.

So I focused in on the vector that was causing the trouble, and didn’t see anything obviously wrong – those timestamps looked just like the other columns of timestamps that had worked thus far.

There were some blanks, but there were blanks in the other columns too, and besides, as.Date("") is just NA, right?

It depends!

First, converting NA to class Date just returns an NA:

> as.Date(NA)
[1] NA

Next, converting a vector of character dates to class Date will convert blanks to NA:

> as.Date(c('2017-11-25', ''))
[1] "2017-11-25" NA

So what do you think as.Date('') will return? NA, right?

> as.Date('')
Error in charToDate(x) : 
  character string is not in a standard unambiguous format


I don’t know of a good explanation for this, but the summary point is: a blank character value in the first element of a vector being converted to Date will cause an error, while blanks later in the vector will be quietly and appropriately converted to NA.

If you’re not sure what the incoming data will look like, it might make sense to only convert dates where the incoming values are not NA or blank, and fill the rest of the converted vector with NAs.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: