rmatrixlmcausality

Column wise granger's causal tests in R


I have 2 matrices of different parameters: M1and M3 with the same dimensions. I'll like to do a column wise grangertest in R.

M1<- matrix( c(2,3, 1, 4, 3, 3, 1,1, 5, 7), nrow=5, ncol=2) 
M3<- matrix( c(1, 3, 1,5, 7,3, 1, 3, 3, 4), nrow=5, ncol=2)

I'll want to do a granger's causality test to determine if M2 granger causes M1. My actual Matrices contain more columns and rows but this is just an example. The original code between two vectors is below:

library(lmtest)
data(ChickEgg)
grangertest(chicken ~ egg, order = 3, data = ChickEgg)

How do I write this for a column wise analysis such that a matrix with 2 rows ( "F[2]" and "Pr(>F)[2]") and two columns is returned as results please?


Solution

  • Does this go into the right direction?

    library(lmtest)
    
    M1<- matrix( c(2,3, 1, 4, 3, 3, 1,1, 5, 7), nrow=5, ncol=2) 
    M3<- matrix( c(1, 3, 1,5, 7,3, 1, 3, 3, 4), nrow=5, ncol=2)
    
    g <- list()
    for (i in 1:ncol(M1)){
    g[[i]]  <- grangertest(M1[ ,i] ~ M3[ ,i])
    }
    
    foo <- function(x){ 
      F <- x$F[2] 
      P <- x$`Pr(>F)`[2]
      data.frame(F = F, P = P)
      }
    
    do.call(rbind, lapply(g, foo))
    
              F         P
    1 0.3125000 0.6754896
    2 0.1781818 0.7457180