Strohmi
Strohmi

Reputation: 523

Automatically create date sequences with different starting dates in R

I can create the desired date sequences using the following code:

DateTwoWeeks1 <- seq(as.Date("2010/8/6"), as.Date("2011/8/5"), by = "2 weeks")
DateTwoWeeks2 <- seq(as.Date("2010/8/7"), as.Date("2011/8/5"), by = "2 weeks")
DateTwoWeeks3 <- seq(as.Date("2010/8/8"), as.Date("2011/8/5"), by = "2 weeks")

However, I would like to automate the creation of the date sequences for 14 different starting dates. I would like to have one time series starting on the 6th of August 2010, the next time series starting on the 7th, so on until the 19th of August 2010.

How can I automate this? I tried it using the "paste" function but I couldn't get the following code to work:

for (i in 6:19){
TimeTwoWeeks[i] <- seq(as.Date(paste("2010/8/", i)), as.Date("2011/8/5"), by = "2 weeks")
}

Any direct help or linkage to other websites/posts is greatly appreciated.

Upvotes: 2

Views: 1990

Answers (2)

Josh O&#39;Brien
Josh O&#39;Brien

Reputation: 162451

Here you go:

TimeTwoWeeks <- lapply(as.Date("2010/8/6") + 0:13, 
                       function(X) seq(X, as.Date("2011/8/5"), by = "2 weeks"))

Upvotes: 5

Brandon Bertelsen
Brandon Bertelsen

Reputation: 44688

If you want to create a list of the time series you could adjust as follows:

TimeTwoWeeks <- list()

for (i in 6:19){
TimeTwoWeeks[[i-5]] <- seq(as.Date(paste("2010/8/", i)), as.Date("2011/8/5"), by = "2 weeks")
}

Upvotes: 1

Related Questions