3

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?

Joke O.
  • 515
  • 6
  • 29
  • It is giving me errors. – akrun Jun 23 '16 at 07:16
  • Yes Akron. Thats because ti is originally meant for two vectors. i'll add that now. – Joke O. Jun 23 '16 at 07:21
  • I just added the original code from the lmtest library using the "ChickEgg" data. I need it rewritten such that I can do the analysis between two columns from difference matrices rather than from the same matric or data frame. – Joke O. Jun 23 '16 at 07:31
  • Can you check the solution posted by me? – akrun Jun 23 '16 at 07:43

2 Answers2

5

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
Alex
  • 4,925
  • 2
  • 32
  • 48
5

We can use sapply

sapply(1:ncol(M1), function(i) {
       m1 <- grangertest(M1[,i]~M3[,i])
       data.frame(F=m1$F[2], p=m1$`Pr(>F)`[2])})
#     [,1]      [,2]     
#F 0.3125    0.1781818
#p 0.6754896 0.745718 
akrun
  • 874,273
  • 37
  • 540
  • 662