The use of dates can frequently be problematic because there is such a wide range of format used to store data information. The R system has various facilities for defining and working with dates and can handle a wide range of formats that might be encountered in a set of data.
The function as.Date can convert a string into a Date object using a user specified format, which can take various forms. The first argument to the function is a character string with the date and the second argument is a second string that provides information about the specific format. The format specifiers use a percent symbol followed by a character, e.g. %d indicates that a day is being specified and %m corresponds to a month etc. If the parts of the date are separated by a symbol such as a slash or a dash then these are included in the format specifier.
If the date is in the form 01/04/2009 then the format string would be %d/%m/%Y. The upper case Y indicates that the year includes century information which is a safer format to use so that there is no ambiguity in any calculations. The following code will convert the date from a character string into a Date object:
> date1 = "01/04/2009" > as.Date(date1, format = "%d/%m/%Y") [1] "2009-04-01" |
A simple alternative would be where a dash is used to separate the day, month and year:
> date2 = "07-04-2002" > as.Date(date2, format = "%d-%m-%Y") [1] "2002-04-07" |
We can compare two dates to see whether one is before the other:
> date1 < date2 [1] TRUE |
There are other operations that we can perform on dates.