3

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.

Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
Nick
  • 3,262
  • 30
  • 44
  • 1
    See http://stackoverflow.com/questions/14843439/problems-adding-a-month-to-x-using-posixlt-in-r-need-to-reset-value-using-as-d/14847439#14847439 – G. Grothendieck Oct 01 '15 at 15:22

2 Answers2

3

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.

LyzandeR
  • 37,047
  • 12
  • 77
  • 87
2

Is that what you are looking for?

today = Sys.Date()
lastSixMonths = seq(today, length.out=6, by="-1 month")

print(lastSixMonths)
# [1] "2015-10-01" "2015-09-01" "2015-08-01" "2015-07-01" "2015-06-01"
# [6] "2015-05-01"