以下代码运行,但不返回(950数值)我所期望的(想要)。在以下代码中,result
是一个包含72行和3列的矩阵。 作为输出,我希望有一个包含72列和 length(spots)
行的矩阵。我尝试初始化fcasts<- matrix(0, nrow=length(spots), ncol=72)
,但代码没有运行。
y<- ts(rnorm(1000),start = 1850, frequency=1)
library(forecast)
#Searching for the best models
order.matrix<-matrix(0,nrow = 3, ncol = 6 * 2 * 6)
aic.vec<- numeric(6 * 2 * 6)
k<-1
for(p in 0:5) for(d in 0:1) for(q in 0:5){
order.matrix[,k]<-c(p,d,q)
aic.vec[k]<- AIC(Arima(y, order=c(p,d,q)))
k<-k+1
}
ind<- order(aic.vec,decreasing=F)
aic.vec<- aic.vec[ind]
order.matrix<- order.matrix[,ind]
order.matrix<- t(order.matrix)
result<- cbind(order.matrix,aic.vec)
SlideFunction<- function(data, window, step){
total<- length(data)
spots<- seq(from=1, to=(total-window), by=step)
fit<- vector(mode="list",length=72)
#fcasts<- matrix(0,nrow=length(spots),ncol=72)
fcasts<- numeric(length(spots))
for(i in 1:length(spots)){
for(j in 1:72){
p<- result[j,1]
d<- result[j,2]
q<- result[j,3]
#Note I am using Arima(in forecast package) not arima
fit[[j]]<- Arima(data[spots[i]:(spots[i]+window)], order=c(p,d,q), method="CSS")
fcasts[i]<- forecast(fit[[j]], h=step)$mean
#I expected(would like to have) 72 one-step ahead prediction for each fcasts i.e, store values for each arima model.
}
}
return(fcasts)
}
SlideFunction(y,50,1)
有人可以帮帮我吗?
答案 0 :(得分:0)
我认为这就是你想要的:
SlideFunction<- function(data, window, step) {
total<- length(data)
spots<- seq(from=1, to=(total-window), by=step)
fcasts<- matrix(0,nrow=length(spots),ncol=72)
for(i in 1:length(spots)) {
for(j in 1:72){
p<- result[j,1]
d<- result[j,2]
q<- result[j,3]
fit <- Arima(data[spots[i]:(spots[i]+window)], order=c(p,d,q), method="CSS")
fcasts[i, j] <- forecast(fit, h=step)$mean
}
}
return(fcasts)
}
SlideFunction(y,50,1)
但这需要很长时间才能完成,我没有耐心等待。我尝试使用较小的数据集:
y<- ts(rnorm(100),start = 1850, frequency=1)
知道结果是正确的,和5而不是72。