2

When I want to list all the months between two dates, seq.Date seems to skip dates. I am definitely making a mistake in my code somewhere, but it is so simple, can't seem to get it right.

Help would be appreciated.

seq.Date(as.Date("2017-01-31"),as.Date("2017-06-30"),by = "months")

Regards, Aksel

Aksel Etingu
  • 195
  • 2
  • 15
  • Probably safer doing `seq.Date(as.Date("2017-02-01"),as.Date("2017-07-01"),by = "months")` – David Arenburg Feb 15 '18 at 15:02
  • Related: [Add/subtract 6 months (bond time) in R using lubridate](https://stackoverflow.com/questions/22628863/add-subtract-6-months-bond-time-in-r-using-lubridate), i.e. the part with "Add and subtract months to a date without exceeding the last day of the new month" – Henrik Feb 15 '18 at 15:07

3 Answers3

6

If you really need the last day of the month, one possibility would be to construct a sequence of the first day of the following months and then subtract 1 day. For example:

> seq.Date(as.Date("2017-02-01"),as.Date("2017-07-01"),by = "months") - 1
[1] "2017-01-31" "2017-02-28" "2017-03-31" "2017-04-30" "2017-05-31" "2017-06-30"
Michael Lugo
  • 378
  • 3
  • 9
1

Its because your dates are the last day of the month, and I believe seq.Date will add the number of days from the month that it started in.

If we look at diff of the output from your example:

seq.Date(as.Date("2017-01-31"),as.Date("2017-06-30"),by = "months")
[1] "2017-01-31" "2017-03-03" "2017-03-31" "2017-05-01" "2017-05-31"

diff(seq.Date(as.Date("2017-01-31"),as.Date("2017-06-30"),by = "months"))
Time differences in days
[1] 31 28 31 30

So it looks like seq.Date is adding 31 days because it starts in January, and then adds February's 28 days etc.

Probably better to use different dates, and maybe combining with some lubridate floor_date or ceiling_date

Matt W.
  • 3,692
  • 2
  • 23
  • 46
0

I think another solution might be to reduce your initial date to the first day of the month, and after your sequence is generated, to use the function LastDayInMonth from package bsts:

initial_date <- as.Date("2017-01-31")
day(initial_date) <- 1 # This is only in case you can't use first date of month
# in the initial assignment.
# As when you have several dates and you want to automate process.
desired_sequence <- seq.Date(initial_date,as.Date("2017-06-30"),by = "months")
library(bsts)
desired_sequence <- LastDayInMonth(desired_sequence)
panchtox
  • 634
  • 7
  • 16