0

I'm trying to use the rollapply function from the zoo package to estimate Granger causality with a rolling window, the grangertest function is from the package lmtest, I have monthly data span over the period 1976-1984.

            y       y1
Jan 1970 7.468513 7.672292
Feb 1970 7.475906 7.468513
Mar 1970 7.448334 7.475906
Apr 1970 7.351158 7.448334
May 1970 7.362011 7.351158
Jun 1970 7.326466 7.362011

I used the below-described codes but none of them seems to work

rol.c <- rollapply(mydata, width = 24,
FUN = function(z) coef(grangertest(mydata, order = 6)), 
by.column = FALSE, align = "right")

rol.cs <- function(x) c(granger.test(x, p = 6))
rollapplyr(mydata, 24, granger.test, by.column = FALSE )

Any help is deeply appreciated.

Ameer
  • 105
  • 11

1 Answers1

2

The function used in rollapply must return a vector or matrix.

rollapplyr(z, 24, function(x) as.matrix(grangertest(x)), by.column = FALSE)
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • when I refer to the data in the code, by default it takes the first variable as dependent and the second variable as independent, but what if want to specify the causal relationship from y1 to y `y~y1` and vice-versa `y1~y`, how can I adjust the code for this purpose? – Ameer Mar 25 '19 at 09:59
  • 1
    Can use `z[, c("abc", "xyz")]` to use the indicated columns or `function(x) as.matrix(grangertest(x[, "abc"], x[, "xyz"]))` – G. Grothendieck Mar 25 '19 at 13:09
  • I tried to use the same function with `rcorr' from `Hmisc` package like this: `rollapplyr(z, 24, function(x) rcorr(x, type=c("spearman")), by.column = FALSE)` and returned the following lines `Dec 1996 Numeric,4 Integer,4 Numeric,4`, all the other lines appear like this, could you help me to fix this problem? – Ameer Mar 29 '19 at 15:01
  • You must wrap rcorr within a function that converts the output of rcorr to to a vector or matrix and use that function in rollapply. – G. Grothendieck Mar 29 '19 at 18:47