Reputation: 2085
I've got starting date and ending date, like below:
date1 <- '01-03-2011'
date2 <- '30-09-2013'
Based on this I would like two create a vector containing following months and years, something like below:
months <- c(3:12, 1:12, 1:9)
years <- c(rep(2011, 10), rep(2012, 12), rep(2013, 9))
What's the fastest way to do this?
Upvotes: 0
Views: 2602
Reputation: 269664
Create a yearmon vector by month and then pick off the years and months:
library(zoo)
fmt <- "%d-%m-%Y"
ym <- seq(as.yearmon(date1, fmt), as.yearmon(date2, fmt), by = 1/12)
years <- as.integer(ym)
months <- cycle(ym)
In terms of magrittr pipes:
library(magrittr)
library(zoo)
fmt <- "%d-%m-%Y"
data.frame(date1, date2) %$%
seq(as.yearmon(date1, fmt), as.yearmon(date2, fmt), by = 1/12) %>%
{ data.frame(year = as.integer(.), month = cycle(.)) }
Upvotes: 0
Reputation: 18681
With lubridate
:
library(lubridate)
dates <- seq(dmy(date1), dmy(date2), by = 'month')
months <- month(dates)
years <- year(dates)
or with format
in Base R:
months <- as.numeric(format(dates, "%m"))
years <- as.numeric(format(dates, "%Y"))
Output:
> months
[1] 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5
[28] 6 7 8 9
> years
[1] 2011 2011 2011 2011 2011 2011 2011 2011 2011 2011 2012 2012 2012 2012 2012 2012
[17] 2012 2012 2012 2012 2012 2012 2013 2013 2013 2013 2013 2013 2013 2013 2013
Upvotes: 0
Reputation: 6768
Try:
date1 <- "01-03-2011"
date2 <- "30-09-2013"
dates <- seq(as.Date(date1, "%d-%m-%Y"), as.Date(date2, "%d-%m-%Y"), by = "month")
as.numeric(substring(dates, 6, 7)) # months
# [1] 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3 4 5 6 7 8 9
as.numeric(substring(dates, 1, 4)) # years
# [1] 2011 2011 2011 2011 2011 2011 2011 2011 2011 2011 2012 2012 2012 2012 2012 2012 2012 2012 2012 2012 2012 2012 2013
#[24] 2013 2013 2013 2013 2013 2013 2013 2013
Upvotes: 4