问题描述
我有一个R
函数,如下所示:
## 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)
#n=10; phi <- 0.6; order <- c(1,0)
bootstrap1 <- function(n,phi){
ts <- arima.sim(n,model = list(ar=phi,order = c(1,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))
}
使用以下R
命令调用该函数:
set.seed(1,kind = "L'Ecuyer-CMRG")
for (i in 1:3) {
print(bootstrap1(10,0.5))
}
我有
##$BOOTSTRAPS
## 2 3 4 5 6 7 8 9
## [1,] 0.8920703 0.703974 0.6990448 0.714255 1.308236 0.809914 0.5315476 0.8175382
##$BOOTSTRAPS
## 2 3 4 5 6 7 8 9
## [1,] 1.87805 1.432904 1.587332 2.233088 2.266381 1.838313 2.189185 1.154926
##$BOOTSTRAPS
## 2 3 4 5 6 7 8 9
## [1,] 4.505243 4.417204 4.741331 4.791572 3.614339 3.946822 4.535057 3.571953
这就是我所期待的
## 2 3 4 5 6 7 8 9
## [1,] 0.8920703 0.703974 0.6990448 0.714255 1.308236 0.809914 0.5315476 0.8175382
## [2,] 1.87805 1.432904 1.587332 2.233088 2.266381 1.838313 2.189185 1.154926
## [3,] 4.505243 4.417204 4.741331 4.791572 3.614339 3.946822 4.535057 3.571953
如何使我的R
代码服从我的思想?我希望显示列标签。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)