I'm trying to create a function that get all the months between two months into a list:
date1<- 201305
date2<- 201511
months <- function(date1,date2){}
And I want it return a list like this:
201305
201306
201307
...
201509
201510
201511
I'm trying to create a function that get all the months between two months into a list:
date1<- 201305
date2<- 201511
months <- function(date1,date2){}
And I want it return a list like this:
201305
201306
201307
...
201509
201510
201511
First, we need to create dates. What you supply is not yet a date as it misses a day--so we add one:
R> d1 <- as.Date(paste0("201305","01"), "%Y%m%d")
R> d2 <- as.Date(paste0("201511","01"), "%Y%m%d")
Given two dates, getting a sequence of dates is trivial: a call to seq()
. Equally trivial to format in the way you want:
R> dat <- format(seq(d1,d2,by="month"), "%Y%m")
We check the beginning and end:
R> head(dat)
[1] "201305" "201306" "201307" "201308" "201309" "201310"
R> tail(dat)
[1] "201506" "201507" "201508" "201509" "201510" "201511"
R>
Now, as a function:
datseq <- function(t1, t2) {
format(seq(as.Date(paste0(t1,"01"), "%Y%m%d"),
as.Date(paste0(t2,"01"), "%Y%m%d"),by="month"),
"%Y%m")
}
This can be done using the yearmon
class in the zoo package:
library(zoo)
ym1 <- as.yearmon(as.character(date1), "%Y%m") # convert to yearmon
ym2 <- as.yearmon(as.character(date2), "%Y%m") # ditto
s <- seq(ym1, ym2, 1/12) # create yearmon sequence
as.numeric(format(s, "%Y%m")) # convert to numeric yyyymm
giving:
[1] 201305 201306 201307 201308 201309 201310 201311 201312 201401 201402
[11] 201403 201404 201405 201406 201407 201408 201409 201410 201411 201412
[21] 201501 201502 201503 201504 201505 201506 201507 201508 201509 201510
[31] 201511
or you might prefer to use s
which is a yearmon class variable which looks like this but sorts correctly and can be used in plotting:
> s
[1] "May 2013" "Jun 2013" "Jul 2013" "Aug 2013" "Sep 2013" "Oct 2013"
[7] "Nov 2013" "Dec 2013" "Jan 2014" "Feb 2014" "Mar 2014" "Apr 2014"
[13] "May 2014" "Jun 2014" "Jul 2014" "Aug 2014" "Sep 2014" "Oct 2014"
[19] "Nov 2014" "Dec 2014" "Jan 2015" "Feb 2015" "Mar 2015" "Apr 2015"
[25] "May 2015" "Jun 2015" "Jul 2015" "Aug 2015" "Sep 2015" "Oct 2015"
[31] "Nov 2015"
For example this works:
plot(seq(31) ~ s)
I know this is an old post but incase someone was having a similar issue to me I hope this can be helpful. If you're looking for the months between 2 dates, lets say
d1 = as.Date("2022-01-25")
d2 = as.Date("2022-02-13")
seq(as.Date(d1), as.Date(d2), by = "month")
[1] "2022-01-25"
It does not give back the desired output of both January and February. I noticed this is because the 'day' portion of the date needs to be the same (or less than) for the first date.
What I opted to do was mutate the first date as so:
d1 = paste0(substr(d1, 1,7), "-01")
seq(as.Date(d1), as.Date(d2), by = "month")
[1] "2022-01-01" "2022-02-01"
This way you will always get the year months that you desire but not necessarily the day portion.