如何在 R 中重复 N 次连续的行

How to Repeat some consecutive lines Nth Times in R

如何连续重复我的第 22 行到第 26 行十次,并将第 26 行的结果从第一行添加到第 10 行,最后在我的 r 代码中得到连续 10 次总和的平均值:

# simulate arima(1,1,0)
library(forecast)
set.seed(100)
wn <- rnorm(10, mean = 0, sd = 1)
ts <- wn[1:2]
for (i in 3:10){
  ts<-arima.sim(n=10,model=list(ar=-0.7048,order=c(1,1,0)),start.innov=4.1,n.start=1,innov=wn)
}
ts <-ts[-1]
#
# write the function for RMSE
rmse <- function(x) {
  m <- auto.arima(x)
  acu <- accuracy(m)
  acu[1, 2]
}
#
t<-length(ts)# the length of the time series
l<- 2# block size
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, 1000) # resamples the blocks
unlist<-unlist(res, use.names = F) # unlist the bootstrap series
tsunlist<-ts(unlist) # turns the bootstrap series into time series data
# use the RMSE function
RMSE <- rmse(tsunlist)

以上R代码分步执行以下算法:

  1. 模拟ARIMA(1,1,0)时间序列(第1行到第9行)
  2. 将时间序列分成大小为 2 的块(第 18 行到第 21 行)
  3. 对每个块随机重采样 1000 次(第 22 行到第 23 行)
  4. 将重采样序列重新排列为时间序列数据(第 24 行)
  5. 获取重采样时间序列的 RMSE(第 26 行)

我想重复步骤3到5 100次,将步骤5产生的结果加起来100次,取结果的平均值。

这里是执行 100 次重采样的方法。用这个替换从第 22 行开始的代码。

finalresult <- vector() #initialize vector to receive result from for loop
for(i in 1:100){
   res<-sample(blk, replace=T, 1000) # resamples the blocks
   res.unlist<-unlist(res, use.names = F) # unlist the bootstrap series
   tsunlist<-ts(res.unlist) # turns the bootstrap series into time series data
   # use the RMSE function
   RMSE <- rmse(tsunlist)
   finalresult[i] <- RMSE # Assign RMSE value to final result vector element i
}

运行 循环后,您将在 finalresult 对象中找到结果。

finalresult
  [1] 0.4695763 0.4702997 0.4727734 0.4677841 0.4633566 0.4619570 0.4645237 0.4657333 0.4734756 0.6035923 0.4676718 0.4563636
 [13] 0.4653432 0.4741868 0.4638185 0.4679926 0.4652872 0.4644442 0.4673774 0.4654423 0.4574012 0.4613827 0.4689168 0.4652262
 [25] 0.4621680 0.4714052 0.4544405 0.4781833 0.4640436 0.4708187 0.4562165 0.4631720 0.4638906 0.4654569 0.4691919 0.4644442
 [37] 0.4635361 0.4657427 0.4682825 0.4626979 0.4636363 0.4562305 0.4582826 0.4689343 0.4648181 0.4659912 0.4597617 0.4701386
 [49] 0.4678786 0.4658028 0.4633929 0.4759015 0.4719038 0.4685480 0.4639831 0.4663984 0.4631158 0.4636240 0.4677248 0.4680744
 [61] 0.4633999 0.4734937 0.4545364 0.4671157 0.4656818 0.4638791 0.4676848 0.4650673 0.4710859 0.4680129 0.4641621 0.4632793
 [73] 0.4664942 0.4596942 0.4643477 0.4626547 0.4684443 0.4572568 0.4695198 0.4566412 0.4650888 0.4643392 0.4603766 0.4694628
 [85] 0.4579581 0.4627443 0.4729837 0.4668802 0.4723182 0.4688657 0.4684541 0.4655471 0.4687285 0.4504862 0.4599657 0.4660643
 [97] 0.5093069 0.4620558 0.4655066 0.4682742