Creating four separate weeks for each calendar month in R

I have a weekly dataset that roughly spans 11 years. The problem is that not every week starts on the 1st of the month, and not every week ends on the 7th of the month.

I tried to create a sequence for 1 month per week to see the corresponding dates, however the month of January (which is 31 days) ends on the 29th:

seq(as.Date("2004-01-01"), as.Date("2004-01-31"), 'weeks')
[1] "2004-01-01" "2004-01-08" "2004-01-15" "2004-01-22" "2004-01-29"

      

I need to create a sequence of weekly dates where each week of each month starts on the 1st and ends on either the 28th (for February) or 30 or 31 (for others). Is it possible? Any help is appreciated.

+2


source to share


1 answer


Try

begin <- seq(as.Date('2004-01-01'), as.Date('2014-02-01'), by='1 month')
end <- begin-1
lst <- split(v1, list(month(v1),year(v1)), drop=TRUE)
res <- unsplit(Map(function(x,y,z) {
      x[c(1, length(x))] <- c(y,z)
      x}, 
   lst, begin[-length(begin)], end[-1L]), list(month(v1), year(v1)))
head(res)
#[1] "2004-01-01" "2004-01-08" "2004-01-15" "2004-01-22" "2004-01-31"
#[6] "2004-02-01"
tail(res)
#[1] "2013-12-31" "2014-01-01" "2014-01-09" "2014-01-16" "2014-01-23"
#[6] "2014-01-31"

      



data

v1 <- seq(as.Date("2004-01-01"), as.Date('2014-01-31'), 'week')

      

+2


source







All Articles