在 R 中为每个日历月创建四个单独的星期

在 R 中为每个日历月创建四个单独的星期

问题描述:

我有一个每周数据集,大致涵盖 11 年.问题是不是每个星期都从当月的 1 号开始,也不是每个星期都在当月的 7 号结束.

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.

我试图以周为单位创建 1 个月的序列以查看相应的日期,但是 1 月(即 31 天)在 29 日结束:

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"

我需要创建一系列每周日期,每个月的每周从 1 号开始,到 28 日(2 月)、30 日或 31 日(其他)结束.这甚至可能吗?非常感谢任何帮助.

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.

尝试

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"

数据

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