4

我是 R 新手,正在尝试在 30 个观察滚动窗口内计算自举标准偏差 (sd) 和相关标准误差。如果我只想要 sd,下面的函数会适当地执行滚动窗口。但是当我使用引导包添加引导功能时,我得到了下面指定的错误。我收集到我正在尝试将引导结果存储在一个大小不正确的向量中。有没有人对如何在新矩阵的行中存储每个窗口的引导 sd 和相关的 stderror 有任何建议?然后,目标是沿时间序列绘制每个窗口的 sd 和相关的 95% 置信区间。提前感谢您的帮助。

> head(data.srs)
    LOGFISH
1  0.8274083
2  1.0853433
3  0.8049845
4  0.8912097
5  1.3514569
6  0.8694499


###Function to apply rolling window

rollWin <- function(timeSeries,  windowLength) 
{
  data<-timeSeries
  nOut <- length(data[, 1]) - windowLength + 1
  out <- numeric(nOut)
  if (length(data[,1]) >= windowLength)
  {
    for (i in 1:nOut) 
      { 
      sd.fun <- function(data,d)sd(data[d], na.rm = TRUE)
      out[i] <- boot(data[i:(i + windowLength - 1), ], sd.fun, R=1000)
      }
  }
  return (list(result=out))
} 

###run rolling window function. ex. rollWin(data, windowlength)
a.temp<-rollWin(data.srs,30)


> warnings()
Warning messages:
1: In out[i] <- boot(data[i:(i + windowLength - 1), ], sd.fun,  ... :
  number of items to replace is not a multiple of replacement length
4

1 回答 1

1

你可以简化很多。我不熟悉这个boot包,但是我们可以很容易地使用该函数沿向量滚动函数rollapply,然后我们可以使用该replicate函数制作引导样本:

# Create some data, 12 items long
r <- runif(12)
# [1] 0.44997964 0.27425412 0.07327872 0.68054759 0.33577348 0.49239478
# [7] 0.93421646 0.19633079 0.45144966 0.53673296 0.71813017 0.85270346


require(zoo)

# use rollapply to calculate function alonga  moving window
# width is the width of the window
sds <- rollapply( r , width = 4 , by = 1 , sd )
#[1] 0.19736258 0.26592331 0.16770025 0.12585750 0.13730946 0.08488467
#[7] 0.16073722 0.22460430 0.22462168


# Now we use replicate to repeatedly evaluate a bootstrap sampling method
# 'n' is number of replications
n <- 4
replicate( n , rollapply( r , width = n , function(x) sd( x[ sample(length(x) , repl = TRUE) ] ) ) )



#            [,1]      [,2]       [,3]      [,4]
# [1,] 0.17934073 0.1815371 0.11603320 0.2992379
# [2,] 0.03551822 0.2862702 0.18492837 0.2526193
# [3,] 0.09042535 0.2419768 0.13124738 0.1666012
# [4,] 0.17238705 0.1410475 0.18136178 0.2457248
# [5,] 0.32008385 0.1709326 0.32909368 0.2550859
# [6,] 0.30832533 0.1480320 0.02363968 0.1275594
# [7,] 0.23069951 0.1275594 0.25648052 0.3016909
# [8,] 0.11235170 0.2493055 0.26089969 0.3012610
# [9,] 0.16819174 0.2099518 0.18033502 0.0906986

每列表示 rollapply,它在应用之前引导当前窗口中的观察sd

于 2013-04-29T21:51:19.150 回答