Here you go. Basic functions only:
last.days.of.month <- function(dt) {ldt<- as.POSIXlt(dt) ldt$mon <- ldt$mon+1 ldt$mday <- 1 return(format( ldt -1, "%Y-%m-%d"))} last.days.of.month(as.Date(c("2010-01-06","2010-03-06", "2010-02-06")) ) # [1] "2010-01-31" "2010-03-31" "2010-02-28" seq.ldom <- function(dt, nmonths) {ldt<- rep(as.POSIXlt(dt)[1], nmonths) ldt$mon <- ldt$mon+seq(1:nmonths) ldt$mday <- 1 return(format( ldt -1, "%Y-%m-%d"))} seq.ldom(as.Date("2010-01-06"), 5) #[1] "2010-01-31" "2010-02-28" "2010-03-31" "2010-04-30" #[5] "2010-05-31"
Oh, for some reason I thought you needed the last days of the month. Sorry for the useless code. The first days of the month are not difficult.
seq.fdom <- function(dt, nmonths) {ldt<- rep(as.POSIXlt(dt)[1], nmonths) ldt$mon <- ldt$mon+seq(0:(nmonths-1)) ldt$mday <- 1 return(format( ldt , "%Y-%m-%d"))} seq.fdom(as.Date("2010-01-06"), 5)
And get the previous months:
seq.prior.fdom <- function(dt, nmonths) {ldt<- rep(as.POSIXlt(dt)[1], nmonths) ldt$mon <- ldt$mon-rev(0:(nmonths-1)) ldt$mday <- 1 return(format( ldt , "%Y-%m-%d"))} seq.prior.fdom(as.Date("2010-01-06"), 5)
I think the basic principle is clear (unless you beat the oars with a canoe to death.)
source share