Search code examples
rrollapply

rollaplly for time series


I have a data set with 358 rows, a quick look is as follows

>        unempts gdpts
> [1,]    7.03   4.2
> [2,]    7.17   3.7
> [3,]    6.97   3.2
> [4,]    6.83   2.9
> [5,]    6.60   2.7
> [6,]    6.27   3.4

I need to run a regression of Column 1 on Column 2, for 60 rolling windows and save all results in matrix so that I can plot the same and run HAC.

I tried the following:

regRO <- rollapply(datam, 60, lm, by.column = TRUE,fill=NA)

but get an error as follows

Error in formula.default(object, env = baseenv()) : invalid formula

Please advise what needs to be changed.


Solution

  • You have to specify the function call explicitly so that X is first converted to a data frame to satisfy the input requirements of lm:

    library(zoo)
    
    set.seed(123) # ensure runif in next line uses same random numbers each time run
    datam <-matrix(runif(200),ncol=2)
    
    out <- rollapplyr(datam,
              width = 60,
              FUN = function(X) coef(lm(as.data.frame(X))),
              by.column=FALSE,
              fill = NA) # omit fill=NA if NA rows not wanted
    

    giving:

    > tail(out)
           (Intercept)         V2
    [95,]    0.5071618 -0.1041905
    [96,]    0.5015140 -0.1032419
    [97,]    0.5196683 -0.1404855
    [98,]    0.5171599 -0.1401534
    [99,]    0.5122871 -0.1288700
    [100,]   0.5176396 -0.1297019