Reputation: 7725
I have the following loop that creates 7 dates for every input date. This is a small example that completes in no time at all. My actual use case takes much much longer, and I would like to speed it up.
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"
Upvotes: 0
Views: 68
Reputation: 24480
You can try:
y<-rep(dat$dateStart,each=8)+seq(0,7*24*60*60,by=24*60*60)
You create a vector by repeating each element of dat$dateStart
eight times and add it to a second vector which represents the number of seconds to make 0,1,2,3,...,7 days. Since R recycles the shorter object, you obtain your desired result.
Upvotes: 1