![](/img/trans.png)
[英]how to make loop for Johansen cointegration test for multivarite time series and get all possible combinations in Rstudio?
[英]for loop: performing cointegration test for all possible combinations in R
我想弄清楚是否可以找到非平稳时间序列与 ADF 测试的每种组合的协整。 这可以通过以下函数完成:
coint <- function(x,y) {
vals <- data.frame(x,y)
beta <- coef(lm(vals[,2] ~ vals[,1] + 0, data = vals))[1]
(tseries::adf.test(vals[,2]- beta*vals[,1], alternative = "stationary", k = 0))$p.value
}
如果我运行函数 coint(df1, df2),我会得到一个 p 值。 但是,我想为每种可能的组合执行此操作(并将其存储在数据框中)。 我已经知道我可以使用 combn() 函数进行所有可能的组合。 但是,我无法让我的 for 循环正确地为每种可能的组合执行此操作。 也许这个操作也可以用 purrr 包中的函数来完成?
我们欢迎所有的建议! 我还在下面添加了一个示例数据框。
# A tibble: 18 x 5
`1` `2` `3` `4` `5` `
1 416 850 53 78 66
2 407 922 43 82 67
3 410 901 37 84 71
4 412 945 53 95 77
5 409 998 101 83 86
6 375 947 53 86 84
7 364 908 43 87 71
8 377 952 39 95 64
9 387 961 18 109 69
10 352 932 11 102 69
11 332 920 12 108 69
12 318 987 22 121 83
13 320 961 17 124 88
14 325 931 15 145 64
15 328 816 6 169 44
16 315 925 8 156 55
17 309 737 4 176 49
18 273 626 4 193 59
不是最好和最有效的循环,但我认为可以:输入将是一个数据框,其中包含所有要检查的变量
coint <- function(vars) {
d<-as.matrix(vars) #convert data frame to Matrix
n<-length(colnames(vars)) #calculate the total number of variables
m<-combn(n,2) #calculate all possible combinations of pairs for all variables
col_m<-dim(m)[2] #number of all possible combinations
result<-matrix(NA,nrow=col_m,ncol=3) #empty result matrix
colnames(result)<-c("Var_1","Var_2","p_Value")
for (i in 1:col_m){
Var_1<-m[1,i]
Var_2<-m[2,i]
res <- lm(d[,Var_1] ~ d[,Var_2] + 0)$residuals
p<-tseries::adf.test(res, alternative = "stationary", k = 0)$p.value
result[i,1]<-colnames(vars)[Var_1]
result[i,2]<-colnames(vars)[Var_2]
result[i,3]<-p
}
return(result)
}
协整方法是关于 2 个变量的残差需要是平稳的。 我立即将它们从估算中剔除,而不是重新计算它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.