Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using as.Date to get previous n months

Tags:

date

r

as.Date() has a useful function in that it can give you the last n days as, e.g.:

dt <- Sys.Date()-6
> dt
 [1] "2015-09-25"

Is there a way to tell it to give the last six months instead of the last six days?

I need something more precise than 6*30, as it should be the last day of the month.

like image 646
Nick Avatar asked Dec 13 '25 02:12

Nick


1 Answers

You cannot use just Sys.Date to do this but there are ways. The following will give you just the correct months but not the correct days (i.e. the last day of the month):

#Sys.Date will return 2015-10-01 today
dates <- seq( Sys.Date() - months(6), Sys.Date(), '1 month')
dates
[1] "2015-04-01" "2015-05-01" "2015-06-01" "2015-07-01" "2015-08-01" "2015-09-01" "2015-10-01"

However, I found this very nice blog on R-bloggers which defines this function ( I slightly modified it to work with Dates) that returns the last day of the month:

eom <- function(date) {
  # date character string containing POSIXct date
  date.lt <- as.POSIXlt(dates) # add a month, then subtract a day:
  mon <- date.lt$mon + 2 
  year <- date.lt$year
  year <- year + as.integer(mon==13) # if month was December add a year
  mon[mon==13] <- 1
  iso = ISOdate(1900+year, mon, 1, hour=0, tz='')
  result = as.POSIXct(iso) - 86400 # subtract one day
  result + (as.POSIXlt(iso)$isdst - as.POSIXlt(result)$isdst)*3600
}

Now running:

> eom(dates)
[1] "2015-04-30 BST" "2015-05-31 BST" "2015-06-30 BST" "2015-07-31 BST" "2015-08-31 BST" "2015-09-30 BST" "2015-10-31 GMT"

Returns the correct results.

like image 87
LyzandeR Avatar answered Dec 14 '25 14:12

LyzandeR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!