R代码:
library(forecast)
library(FitAR)
set.seed(54321)
c<-0 # Counter for correct model under method
n=50
nsim=10
phi=c(0.5,-0.2)
t=1:n
t.square=t^2
beta1=2
beta2=3
beta3=4
for (i in 1: nsim) {
error<-arima.sim(model=list(ar=phi),n=n,innov=rnorm(n,0,1))
yt=beta1+beta2*t+beta3*t.square+error
dt=cbind(t,t.square)
p<- SelectModel(as.ts(error), lag.max = 15, Criterion = "BIC", Best=1)
f1=Arima(yt, xreg=dt, order=c(p,0,0),include.drift=FALSE, include.constant
= FALSE, method = "ML")
print((coef(f1)))
}
输出:
ar1 ar2 ar3 t t.square
0.9031324 -0.4968706 0.4069485 3.1808610 3.9965791
ar1 t t.square
0.7372397 3.1051317 3.9989081
t t.square
3.178753 3.996895
ar1 t t.square
0.6279603 3.1813097 3.9967204
ar1 t t.square
0.5789377 3.1561776 3.9976448
ar1 ar2 t t.square
0.8023629 -0.2414305 3.1717066 3.9968250
ar1 ar2 t t.square
0.8423128 -0.3565319 3.1768333 3.9966517
ar1 t t.square
0.5170698 3.0990545 3.9987464
ar1 t t.square
0.5521029 3.1356383 3.9978553
ar1 t t.square
0.5280407 3.1679048 3.9972218
模拟数量为10。上面的输出是对2阶AR的估计,变量为t和t.square。
我想让代码在AR(2)有两个系数时得到。这意味着对于每个模拟,如果ar1和ar2存在,则不删除该行。
所以我想得到
ar1 ar2 t t.square
0.8023629 -0.2414305 3.1717066 3.9968250
ar1 ar2 t t.square
0.8423128 -0.3565319 3.1768333 3.9966517
先谢谢您。
答案 0 :(得分:0)
我认为这可以解决问题。首先,可以在while
上使用i
循环,仅在获得所需结果(AR(2))时递增计数器。然后,您可以确定系数矢量的名称包含ar2
而不包含ar3
的条件。然后,仅在那些情况下才保留模拟值。
library(forecast)
library(FitAR)
set.seed(54321)
c<-0 # Counter for correct model under method
n=50
nsim=10
phi=c(0.5,-0.2)
t=1:n
t.square=t^2
beta1=2
beta2=3
beta3=4
out <- array(dim=c(nsim, 4))
colnames(out) <- c("ar1", "ar2", "t", "t.square")
i <- 1
while(i <= nsim){
error<-arima.sim(model=list(ar=phi),n=n,innov=rnorm(n,0,1))
yt=beta1+beta2*t+beta3*t.square+error
dt=cbind(t,t.square)
p<- SelectModel(as.ts(error), lag.max = 15, Criterion = "BIC", Best=1)
f1=Arima(yt, xreg=dt, order=c(p,0,0),include.drift=FALSE, include.constant
= FALSE, method = "ML")
co <- coef(f1)
insim <- ("ar2" %in% names(co)) & !("ar3" %in% names(co))
if(insim){
out[i, ] <- co
i <- i+1
}
}