Creating four separate weeks for each calendar mon

2019-07-11 07:41发布

问题:

I have a weekly data set which roughly covers 11 years. The problem is that not every week begins 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 in weeks 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 whereby each week of each month begins on the 1st and ends on either the 28th (for Feb), 30 or 31 (for others). Is this even possible? Any assistance is greatly appreciated.

回答1:

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')


标签: r time sequence