我是R的新手,我正在尝试计算30观察滚动窗口内的自举标准偏差(sd)和相关的标准误差.如果我只想要sd,下面的函数会适当地执行滚动窗口.但是当我使用启动包添加引导函数时,我得到下面
> 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你可以简化它.我不熟悉启动包,但我们可以很容易地使用rollapply函数在向量上滚动函数,然后我们可以使用复制函数制作自举样本:
# 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之前引导当前窗口中的观察结果.