Date conversion in R can be a real pain. This article provides an introduction to the functionality R offers for converting strings to dates. Converting dates entered as strings into numeric dates in R is relatively simple for a single string and for a vector of strings if you have consistent date information. It is far trickier if the date information is represented inconsistently but hopefully it will be made easier using the
flipTime provides utilities for working with time series and date-time data. The package can be installed from
- A Displayr document.
The functions from the
AsDateTime()build on the convenience and speed of the popular
AsDateTime() are careful to not convert any strings to dates when they are not formatted as dates. Additionally, they will also warn the user when the dates are not in an unambiguous format.
AsDateTime()are very flexible with respect to what they permit as characters to separate the components of the date strings.
AsDate("Jan. 10, 2016")
##  "2016-01-10"
AsDate("Jan/10 - 2016")
##  "2016-01-10"
However, they are also careful to not convert strings to dates that are clearly not dates:
## Error in AsDate("Jan 128"): Could not parse "Jan 128" into a valid
## date in any format.
## Error in AsDate("3.122"): Could not parse "3.122" into a valid date in
## any format.
The above example also demonstrates the default behavior of the functions to throw an error. This occurs when the date strings cannot be interpreted as dates. Both functions have an argument
on.parse.failure, which is used to control this behavior.
AsDate("foo", on.parse.failure = "warn")
## Warning in AsDate("foo", on.parse.failure = "warn"): Could not parse
## "foo" into a valid date in any format.
##  NA
AsDateTime("foo", on.parse.failure = "silent")
##  NA
Both functions provide an argument
us.format, to allow the user to specify whether the date strings are in a U.S. or international format. U.S. format is with the month coming before the day, such as
1988. By contrast, international format, has the day before the month, such as
21-10-1999. The default behavior is to check both formats. In this case, if the format is ambiguous, the date strings will be converted according to the U.S. format. The user will also receive a warning.
## Warning: Date formats are ambiguous, US format has been used.
##  "2010-09-10 22:20:00 UTC"
AsDateTime("9/10/2010 10:20PM", us.format = FALSE)
##  "2010-10-09 22:20:00 UTC"
AsDate() is also able to interpret date intervals or periods, which can be useful when working with aggregated data. If the function encounters date periods, it will convert the start of the period to a date and return it.
##  "2015-10-20"
AsDate("may 2017-september 2017")
##  "2017-05-01"
##  "2015-12-01"