Hi, I’m trying to loop thru a monthly dataset and grab rolling 12 month periods to analyze. I’ll use AirPassengers as an example but its not the data I want to analyze.
AirPassengers is monthly data from 1949 to 1960, 12 years, 12 months per year or 144 rows.
I’ve created a date variable to go with air passengers.
There are 133 groups I’d like to select as below (if I’ve done the math right).
As the loop progresses I’d like to append each 12 month group to the previous. The ultimate dataset should have 133 groups of 12 each or 1596 rows (=133*12)
For loop 1 I’d like to select the 12 rows Jan 1949 to Dec 1949 (rows 1 to 12).
For loop 2 I’d like to select the 12 rows Feb 1949 to Jan 1950 (rows 2 to 13).
And so on …
For loop 133 I’d like to select the 12 rows Jan 1960 to Dec 1960 (rows 133 to 144).
The code below goes haywire. Even though I want base[(i:11+i),] to select row i to row i+11 (12 rows), it’s not doing it. Will appreciate help.
#get the airpassenger data
base <- as.data.frame(AirPassengers)
colnames(base) <-"ap"
#create date variable
d0 = data.frame()
for (y in 1949:1960)
for (m in 1:12) {
ym = c(y,m,1)
d0 = rbind(d0,ym)
}
colnames(d0) <- c("y","m","d")
base$date <-as.Date(with(d0,paste(y,m,d,sep = "-")),"%Y-%m-%d")
#calculate end loop
n=nrow(base)-11
#d2 will contain rolling 12 month groups
d2 = data.frame()
#for loop to select rolling 12 month groups
for (i in 1:n) {
d1 <- as.data.frame(base[(i:11+i),])
d2=rbind(d2,d1)
}