我知道这可能看起来很长,但这是一个与动物园循环相关的简单问题。请继续阅读:
# required libraries:
library(vars)
library(zoo)
# create time series
model <- zoo(x = cbind(rnorm(10),rnorm(10)*2, rnorm(10)*0.2), order.by = as.Date(1:10))
> model
1970-01-02 -0.32247034 -2.8667554 -0.08572468
1970-01-03 -1.33880074 -2.1103700 -0.13123590
1970-01-04 0.68815603 -1.4662238 0.19187887
1970-01-05 0.07128065 0.4218145 0.31121053
1970-01-06 2.18975236 -1.9978415 -0.20815929
1970-01-07 -1.15770760 2.1557006 0.18611448
1970-01-08 1.18168806 -2.3979488 -0.01508919
1970-01-09 -0.52736836 0.4332741 -0.39343907
1970-01-10 -1.45662801 0.2861741 -0.15118073
1970-01-11 0.57296737 -2.1315002 0.09222983
我想创建一个动物园时间序列对象,其中包含每个日期的 VAR 方程的系数,仅使用当时可用的数据。我只想要变量“X”的系数。具体来说,我想循环这些函数:
> coef(VAR(model[1:5]))$x[,1]
x.l1 y.l1 z.l1 const
6.366133 51.897180 -273.933190 -28.856147
> coef(VAR(model[1:6]))$x[,1]
x.l1 y.l1 z.l1 const
-0.1726954 0.5972525 -1.9151799 -0.4963311
> coef(VAR(model[1:7]))$x[,1]
x.l1 y.l1 z.l1 const
-0.3567360 -0.1969814 1.0163298 -0.1171288
> coef(VAR(model[1:8]))$x[,1]
x.l1 y.l1 z.l1 const
-0.54919705 -0.09963062 0.47934378 -0.20755763
> coef(VAR(model[1:9]))$x[,1]
x.l1 y.l1 z.l1 const
-0.4623637 -0.2161147 1.5129717 -0.3003821
> coef(VAR(model[1:10]))$x[,1]
x.l1 y.l1 z.l1 const
-0.5041168 -0.2164998 1.5813547 -0.2684235
并将它们放在适当索引的动物园对象中,例如:
x.l1 y.l2 z.l1 const
1970-01-02 NA NA NA NA
1970-01-03 NA NA NA NA
1970-01-04 NA NA NA NA
1970-01-05 NA NA NA NA
1970-01-06 6.366133 51.897180 -273.933190 -28.856147
1970-01-07 -0.1726954 0.5972525 -1.9151799 -0.4963311
1970-01-08 -0.3567360 -0.1969814 1.0163298 -0.1171288
1970-01-09 -0.54919705 -0.09963062 0.47934378 -0.20755763
1970-01-10 -0.4623637 -0.2161147 1.5129717 -0.3003821
1970-01-11 -0.5041168 -0.2164998 1.5813547 -0.2684235
我已经尝试过了,但它没有创建时间序列对象(仅是最终迭代的结果):
for (i in 2:(nrow(model)-3))
{
b <- coef(VAR(model[1:(ncol(model)+i)]))$x[,1]
}
我还尝试了 rollapply,它创建了一个动物园对象,但数字看起来很奇怪:
rollapply(model, width = seq_along(model[,1])[5:10],
function(x) coef(VAR(x))$x[,1],
by.column = FALSE, align = "right")
x.l1 y.l1 z.l1 const
1970-01-08 0.8259929 -0.4151388 1.1475067 -0.1905136
1970-01-09 -1.5161721 0.6774460 -7.0410817 1.0445796
1970-01-10 -0.1054592 -0.1699834 0.3326742 -0.2718832
1970-01-11 -0.2773018 -0.1760636 0.6023782 -0.1737401
请帮忙。我已经花了两天时间!非常感谢