Working with dates in R
- 1. Working with dates in R
> ###CONVERT CHARACTER TO DATE FORMAT###
> d <- "2012_12_31"
> d1 <- "November 22, 1984"
> d2 <- "15OCT12"
> dd <- as.Date(d, format="%Y_%m_%d")
> str(dd)
Date[1:1], format: "2012-12-31"
>
> dd1 <- as.Date(d1, format="%B %d, %Y")
> str(dd1)
Date[1:1], format: "1984-11-22"
>
> dd2 <- as.Date(d2, format="%d%b%y")
> str(dd2)
Date[1:1], format: "2012-10-15"
>
> ###SUBTRACTING OR ADDING DAYS###
> dd-10
[1] "2012-12-21"
> dd+5
[1] "2013-01-05"
>
> ###SUBTRACTING OR ADDING WEEKS, MONTHS, YEARS##
> seq(dd, by="-1 weeks", length=2)[2]
[1] "2012-12-24"
> seq(dd, by="3 months", length=2)[2]
[1] "2013-03-31"
> seq(dd, by="-2 years", length=2)[2]
[1] "2010-12-31"
>
> ###DEFAULT ORIGIN IN R###
> 0-as.numeric(Sys.Date())
[1] -15735
> as.Date(0-as.numeric(Sys.Date()), origin=Sys.Date())
[1] "1970-01-01"
>
> ###WEEKDAYS###
> dd1
[1] "1984-11-22"
> weekdays(c(dd, dd1, dd2))
[1] "Monday" "Thursday" "Monday"
>
> ###DATE FORMATING###
> dd2
- 2. [1] "2012-10-15"
> format(dd2, format="%a")
[1] "Mon"
> format(dd2, format="%A")
[1] "Monday"
> format(dd2, format="%B")
[1] "October"
> format(dd2, format="%b")
[1] "Oct"
> format(dd2, format="%y")
[1] "12"
> format(dd2, format="%Y")
[1] "2012"
>
> ###DATE DIFFERENCES###
>
> #DAYS#
> dd1; Sys.Date()
[1] "1984-11-22"
[1] "2013-01-30"
> Sys.Date()-dd1
Time difference of 10296 days
> Sys.Date()
[1] "2013-01-30"
>
> #WEEKS#
> difftime(Sys.Date(), dd1, units="weeks")
Time difference of 1470.857 weeks
>
> #MONTHS#
> #http://stackoverflow.com/questions/1995933/number-of-months-between-two-
dates
> monnb <- function(d) { lt <- as.POSIXlt(as.Date(d, origin="1900-01-01"));
+ lt$year*12 + lt$mon }
> mondf <- function(d1, d2) { monnb(d2) - monnb(d1) }
> mondf(as.Date("1984-11-22"), Sys.Date())
[1] 338
>
> #BEGGINING OF THE
> dd1
[1] "1984-11-22"
> beg_month <- as.Date(paste("01", format(dd1,"%m"), format(dd1,"%Y"),
sep="."),format="%d.%m.%Y")
> beg_month
[1] "1984-11-01"
> #LAST DAY OF THE MONTH#
> last_day <- seq(beg_month, length=2, by="1 month")[2]-1
> last_day
[1] "1984-11-30"