Friday 24 July 2015

R: Working with Dates

R provides number of options to work with dates and times. Dates represented by Date class.

Sys.Date() function returns todays date.
> Sys.Date()
[1] "2015-06-11"

Built in as.Date function is used to handle dates.

> x <- as.Date("1970-01-01")
> unclass(x)
[1] 0

Dates are stored internally as number of days since 1970-01-01. So unclass(x) return 0. For the following snippet unclass(x) function return 1.

> x <- as.Date("1970-01-02")
> unclass(x)
[1] 1

The as.Date() function allows various input formats through format argument.

Code
Description
%d
It is a number, represents day of the month.
%m
Number represents month
%b
Represents month in Abbreviated format
$B
Represents month in full name
%y
Year in 2 digits
%Y
Year in 4 digits

> as.Date('6/6/1988',format='%m/%d/%Y')
[1] "1988-06-06"
> as.Date('June 6, 1988',format='%B %d, %Y')
[1] "1988-06-06"
> as.Date('06JUN88',format='%d%b%y')
[1] "1988-06-06"

Return the day of the week
“weekdays()” function takes Date objects and return day of the week.

> weekdays(c(as.Date('1988-06-06'), as.Date('1988-06-11'), as.Date('1988-05-06')))
[1] "Monday"   "Saturday" "Friday" 

For more information, refer to the help section of as.Date function.


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment