Reputation: 2833
I would like to fit an autoregressive AR1 model to a time series data over a rolling window to extract the coefficient for each time step but over a fixed window, say 100.
I can calculate the coefficient for each tilmestep using something like this
dat <- data.frame(Last = runif(10000), time =seq(1, 10000, 1))
roll.ar<-NULL
##loop to calculate the rolling change
for(i in 2:length(dat[,1])){
dat.t<-subset(dat, time<=unique(sort(dat$time))[i])
roll.ar[[i]]<-ar.ols(dat.t$Last, aic = FALSE, order.max = 1, dmean = FALSE, intercept = FALSE)$ar[1]
}
But this doesn't use a fixed window - i.e. each successive calculation uses more data than the last. Any guidance gratefully received.
Upvotes: 0
Views: 458
Reputation: 269644
Below we define a series of 20 values and compute the ar1 coefficient using a window of 10.
library(zoo)
set.seed(123)
dat <- data.frame(Last = runif(20)) # test input
AR <- function(x) {
ar.ols(x, aic = FALSE, order.max = 1, dmean = FALSE, intercept = FALSE)$ar[1]
}
rollapplyr(dat$Last, 10, AR, fill = NA)
## [1] NA NA NA NA NA NA
## [7] NA NA NA -0.2932866 -0.3146008 -0.3142310
## [13] -0.2622454 -0.4233658 -0.1284332 -0.5366662 -0.6037607 -0.3294886
## [19] -0.1573014 -0.1964080
Upvotes: 1