为每个日期输入创建多个日期的向量

时间:2014-10-11 05:21:39

标签: r

我有以下循环,为每个输入日期创建7个日期。这是一个很快就完成的小例子。我的实际用例需要更长的时间,我想加快速度。

library(lubridate)
dat <- data.frame(id=c(1, 2, 3, 4, 5, 6),
                  dateStart=c("2000-01-01", "2000-01-01", "2000-01-02",
                              "2000-01-04", "2000-02-01", "2000-02-03"))
dat$dateStart <- ymd(as.character(dat$dateStart))

for (i in 1:nrow(dat)) {
  x <- seq(dat$dateStart[i], dat$dateStart[i] + days(7), by="1 day")
  if (i==1) {
    y <- x
  } else {
    y <- c(y, x)
  }
}

y
#[1] "1999-12-31 19:00:00 EST" "2000-01-01 19:00:00 EST" "2000-01-02 19:00:00 EST"
#[4] "2000-01-03 19:00:00 EST" "2000-01-04 19:00:00 EST" "2000-01-05 19:00:00 EST"
#[7] "2000-01-06 19:00:00 EST" "2000-01-07 19:00:00 EST" "1999-12-31 19:00:00 EST"
#[10] "2000-01-01 19:00:00 EST" "2000-01-02 19:00:00 EST" "2000-01-03 19:00:00 EST"
#[13] "2000-01-04 19:00:00 EST" "2000-01-05 19:00:00 EST" "2000-01-06 19:00:00 EST"
#[16] "2000-01-07 19:00:00 EST" "2000-01-01 19:00:00 EST" "2000-01-02 19:00:00 EST"
#[19] "2000-01-03 19:00:00 EST" "2000-01-04 19:00:00 EST" "2000-01-05 19:00:00 EST"
#[22] "2000-01-06 19:00:00 EST" "2000-01-07 19:00:00 EST" "2000-01-08 19:00:00 EST"
#[25] "2000-01-03 19:00:00 EST" "2000-01-04 19:00:00 EST" "2000-01-05 19:00:00 EST"
#[28] "2000-01-06 19:00:00 EST" "2000-01-07 19:00:00 EST" "2000-01-08 19:00:00 EST"
#[31] "2000-01-09 19:00:00 EST" "2000-01-10 19:00:00 EST" "2000-01-31 19:00:00 EST"
#[34] "2000-02-01 19:00:00 EST" "2000-02-02 19:00:00 EST" "2000-02-03 19:00:00 EST"
#[37] "2000-02-04 19:00:00 EST" "2000-02-05 19:00:00 EST" "2000-02-06 19:00:00 EST"
#[40] "2000-02-07 19:00:00 EST" "2000-02-02 19:00:00 EST" "2000-02-03 19:00:00 EST"
#[43] "2000-02-04 19:00:00 EST" "2000-02-05 19:00:00 EST" "2000-02-06 19:00:00 EST"
#[46] "2000-02-07 19:00:00 EST" "2000-02-08 19:00:00 EST" "2000-02-09 19:00:00 EST"

1 个答案:

答案 0 :(得分:1)

您可以尝试:

   y<-rep(dat$dateStart,each=8)+seq(0,7*24*60*60,by=24*60*60)

通过重复dat$dateStart的每个元素八次创建一个向量,并将其添加到第二个向量中,该向量表示生成0,1,2,3,...,7天的秒数。由于R回收较短的物体,您将获得所需的结果。