大家下午好
我試圖找到我通過模擬運行生成的時間序列的標準預測誤差,該模擬運行是通過具有 250 次模擬的 sim_11 函式定義的。這在下面的第一批代碼中提供。
第二批創建時間序列模型 (AR(1)) 并嘗試預測接下來的 5 個值,我總共進行了 250 次模擬。對于每次模擬,我應該能夠得到 5 個預測錯誤,在 250 次模擬之后,我應該得到一個包含 250 行和 5 列的結果表。但是,當我嘗試在 for 回圈中設定它時,我最終只有 250 個單個值,而實際上我應該最終得到一個 250 x 5 的表/矩陣。我相信錯誤在
pred_error_AR1_100[i]<-table((pre_AR1_100$se[1]),(pre_AR1_100$se[2]),
(pre_AR1_100$se[3]),(pre_AR1_100$se[4]),
(pre_AR1_100$se[5]), ncol=5)
但是我無法弄清楚格式應該在哪里或格式應該是什么。
先感謝您。
下面提供了兩個代碼批次以供復制。
# Setup the simulation run with 100 observations and 250 simulations
sim_11=function(){
e<-rnorm(200, mean=0, sd=0.2) # Produces 200 white noise values
Y_t=c(0,0) # Fills in the first 2 observations as a lag of 2 can be handled
for (i in 3:length(e)){
f1<- 0.138 (0.316 0.982*Y_t[i-1])*exp(-3.89*(Y_t[i-1])^2)
f2<- -0.437-(0.659 1.260*Y_t[i-1])*exp(-3.89*(Y_t[i-1])^2)
Y_t[i]<-f1*Y_t[i-1] f2*Y_t[i-2] e[i]
}
Y_t<-Y_t[101:200] # Removes the first 100 observations
Y_t # Prints the 100 observations
}
lapply(1:250, function(x) sim_11()) # Provides the results of the 250 simulations
x_100_lstar=replicate(250,sim_11()) # Places all results into one matrix
pred_error_AR1_100=0
# controls<-list(gammaInt=c(0.1,2000), nGamma=50)
for (i in 1:ncol(x_100_lstar)){
AR1_100<-ar(x_100_lstar[,i])
pre_AR1_100<-predict(AR1_100, n.ahead=5)
pred_error_AR1_100[i]<-table((pre_AR1_100$se[1]),(pre_AR1_100$se[2]),
(pre_AR1_100$se[3]),(pre_AR1_100$se[4]),
(pre_AR1_100$se[5]), ncol=5)
}
pred_error_AR1_100
uj5u.com熱心網友回復:
為了讓您的回圈作業,您需要初始化pred_error_AR1_100為一個n逐5矩陣,然后一次修改一行。你不應該table在這里使用。有關構造、訪問和修改矩陣的詳細資訊,請參閱?matrix和?Extract。
n <- ncol(x_100_lstar)
pred_error_AR1_100 <- matrix(NA, n, 5)
for (i in seq_len(n)) {
AR1_100 <- ar(x_100_lstar[, i])
pre_AR1_100 <- predict(AR1_100, n.ahead = 5)
pred_error_AR1_100[i, ] <- pre_AR1_100$se
}
但是,在這些情況下,使用更安全、更快捷apply:
## Here, 'x' represents the result of one realization of 'sim_11()'
f <- function(x) {
AR1_100 <- ar(x)
pre_AR1_100 <- predict(AR1_100, n.ahead = 5)
pre_AR1_100$se
}
## Apply function 'f' to each column of 'x_100_lstar'
pred_error_AR1_100 <- t(apply(x_100_lstar, 2L, f))
在最后一行中,對apply一個5乘n矩陣的結果進行轉置以獲得一個n乘5矩陣。
FWIW,sim_11()如果您初始化Y_t為長度為 200 的向量,速度會稍快一些,如下所示:
Y_t <- rep.int(NA, 200)
Y_t[1:2] <- 0
而不是在每次迭代中將長度增加 1。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/368703.html
上一篇:如何自定義3D散點圖
