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.