2

I would like to generate a sequence of all months between two dates.

I can achieve this with seq.Date :

start <- as.Date("2015-08-01")
end <- as.Date("2015-09-01")
seq <- seq.Date(start, end, by = "month")
[1] "2015-08-01" "2015-09-01"
format(seq, "%Y-%m")
[1] "2015-08" "2015-09"

But it fails if there is less than a month ellapsed between the two dates :

start <- as.Date("2015-08-14")
end <- as.Date("2015-09-03")
seq <- seq.Date(start, end, by = "month")
[1] "2015-08-14"
format(seq, "%Y-%m")
[1] "2015-08"

I can work around with seq by days :

unique(format(seq.Date(start, end, by = "day"), "%Y-%m"))
[1] "2015-08" "2015-09"

But is there a more straightforward way to do this that I'm missing ? Thanks.

Julien Navarre
  • 7,653
  • 3
  • 42
  • 69
  • possible duplicate of [Number of months between two dates](http://stackoverflow.com/questions/1995933/number-of-months-between-two-dates) – phiver Sep 03 '15 at 10:23
  • Maybe this [will](http://stackoverflow.com/questions/1995933/number-of-months-between-two-dates) help – Diego Aguado Sep 03 '15 at 10:24

1 Answers1

6

Since you aren't interested in the days, you can scrap that part of the date and deal with only the months. Do this by adding in an arbitrary day of the month (I've used the first day below, but any day will do as long as they are the same).

start <- as.Date("2015-08-14")
end <- as.Date("2015-09-03")

forced_start <- as.Date(paste0(format(start, "%Y-%m"), "-01"))
forced_end <- as.Date(paste0(format(end, "%Y-%m"), "-01"))

seq_dates <- seq.Date(forced_start, forced_end, by = "month")
format(seq_dates, "%Y-%m")
Benjamin
  • 16,897
  • 6
  • 45
  • 65