在R

时间:2015-07-16 06:54:25

标签: r date seq as.date

我试图产生一个星期的序列,每个月重复一次。

我已经明确地创建了一个月的序列,但我也希望每个月的序列都相同。

sequence2 <- format(seq(as.Date("2004-01-01"), as.Date("2004-01-23"), by =    "week"), "%Y-%m-%d") 

这给了我:

sequence2
[1] "2004-01-01" "2004-01-08" "2004-01-15" "2004-01-22"

我想要这样的事情:

"2004-01-01" "2004-01-08" "2004-01-15" "2004-01-22"
"2004-02-01" "2004-02-08" "2004-02-15" "2004-02-22"
.
.
.

序列应该到2014年

任何帮助都会很棒。

2 个答案:

答案 0 :(得分:1)

我们可以创建一个&#39;日期&#39;序列(&#39; v1&#39;),split基于monthyear的向量。使用lapply循环显示列表并删除日期部分和paste以及前四次观察中的日期(使用substr提取)。

 library(lubridate)
 v1 <- seq(as.Date("2004-01-01"), as.Date("2014-01-23"), by = "week")
 lst <- split(v1, list(month(v1), year(v1)), drop=TRUE)
 days <- substr(v1[1:4],9,10)
 v2 <- unlist(lapply(lst, function(x) {
     sprintf('%s%s', substr(x[1:4], 1,8), days)}), use.names=FALSE)
 v2[1:8]
 #[1] "2004-01-01" "2004-01-08" "2004-01-15" "2004-01-22" "2004-02-01"
 #[6] "2004-02-08" "2004-02-15" "2004-02-22"
 tail(v2,8)
 #[1] "2013-12-01" "2013-12-08" "2013-12-15" "2013-12-22" "2014-01-01"
 #[6] "2014-01-08" "2014-01-15" "2014-01-22"

或另一种选择是

 v1 <- seq(as.Date('2004-01-01'), length.out=4, by = 'week')
 len <- 4*12*10  + 4
 v2 <- rep(v1, len/4)
 v3 <- do.call(paste, c(d1[do.call(order, d1),][1:484,-3], sep="-"))
 res <- paste0(v3, sub('^\\d+-\\d+', '', v2))
 head(res,8)
 #[1] "2004-01-01" "2004-01-08" "2004-01-15" "2004-01-22" "2004-02-01"
 #[6] "2004-02-08" "2004-02-15" "2004-02-22"
 tail(res,8)
 #[1] "2013-12-01" "2013-12-08" "2013-12-15" "2013-12-22" "2014-01-01"
 #[6] "2014-01-08" "2014-01-15" "2014-01-22"

答案 1 :(得分:0)

库'timeDate'可能很有用。它有一个'timeCalendar'函数:

library(timeDate)

t <- matrix(NA,0,4)

for ( year in 2001:2004 )
{
  for ( month in 1:12 )
  {
    t <- rbind(t,rep(NA,4))

    for ( i in 0:3 )
    {
      t[nrow(t),i+1] <- as.character(timeCalendar( y = year,
                                                   m = month,
                                                   d = 7*i+1) )
    }
  }
}