我编写了下面的R函数来完成以下任务:
9s.
ARIMA模型到ARIMA模型的10个时间序列数据集,通过arima.sim()函数
2s、3s、4s、5s、6s、7s、8s,并且对于每个块大小的子系列,RMSE.
的每个子系列都采用重采样的方式,从每个块大小到d18RMSE.>从子系列中获得最佳<>d17模型。
。
## Load packages and prepare multicore process
library(forecast)
library(future.apply)
plan(multisession)
library(parallel)
library(foreach)
library(doParallel)
n_cores <- detectCores()
cl <- makeCluster(n_cores)
registerDoParallel(cores = detectCores())
## simulate ARIMA(1,0, 0)
#n=10; phi <- 0.6; order <- c(1, 0, 0)
bootstrap1 <- function(n, phi){
ts <- arima.sim(n, model = list(ar=phi, order = c(1, 0, 0)), sd = 1)
########################################################
## create a vector of block sizes
t <- length(ts) # the length of the time series
lb <- seq(n-2)+1 # vector of block sizes to be 1 < l < n (i.e to be between 1 and n exclusively)
########################################################
## This section create matrix to store block means
BOOTSTRAP <- matrix(nrow = 1, ncol = length(lb))
colnames(BOOTSTRAP) <-lb
########################################################
## This section use foreach function to do detail in the brace
BOOTSTRAP <- foreach(b = 1:length(lb), .combine = 'cbind') %do%{
l <- lb[b]# block size at each instance
m <- ceiling(t / l) # number of blocks
blk <- split(ts, rep(1:m, each=l, length.out = t)) # divides the series into blocks
######################################################
res<-sample(blk, replace=T, 10) # resamples the blocks
res.unlist <- unlist(res, use.names = FALSE) # unlist the bootstrap series
train <- head(res.unlist, round(length(res.unlist) - 10)) # Train set
test <- tail(res.unlist, length(res.unlist) - length(train)) # Test set
nfuture <- forecast::forecast(train, model = forecast::auto.arima(train), lambda=0, biasadj=TRUE, h = length(test))$mean # makes the `forecast of test set
RMSE <- Metrics::rmse(test, nfuture) # RETURN RMSE
BOOTSTRAP[b] <- RMSE
}
BOOTSTRAPS <- matrix(BOOTSTRAP, nrow = 1, ncol = length(lb))
colnames(BOOTSTRAPS) <- lb
BOOTSTRAPS
return(list(BOOTSTRAPS))
}如果函数被调用如下:
bootstrap1(10, 0.6)我得到以下结果:
##$BOOTSTRAPS
## 2 3 4 5 6 7 8 9
##[1,] 1.287224 2.264574 2.998069 2.349261 1.677791 1.183126 2.021157 1.357658我试图使用Monte Carlo 函数使函数运行三(3)次。。
param_list=list("n"=10, "phi"=0.6)
library(MonteCarlo)
MC_result<-MonteCarlo(func = bootstrap1, nrep=3, param_list = param_list)我得到了下面的error message
MonteCarlo中的错误( func = bootstrap1,nrep = 3,param_list = param_list):func必须返回一个带有命名组件的列表。每个组件都必须是标量。
请帮助我纠正我在函数或MonteCarlo() 函数上做错了什么.
发布于 2020-10-08 16:44:49
根据错误消息,我将尝试将函数的末尾替换为如下所示:
names(BOOTSTRAPS) <- letters[1:10]
return(as.list(BOOTSTRAPS))然后,得到的输出是一个名为letters[1:10]的命名列表。
https://stackoverflow.com/questions/64263776
复制相似问题