Column wise granger's causal tests in R

余生长醉 提交于 2019-12-01 06:51:55

问题


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?


回答1:


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



回答2:


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 


来源:https://stackoverflow.com/questions/37984606/column-wise-grangers-causal-tests-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!