How to calculate loaded loaded values ​​and confidence intervals in R

I am new to R and trying to calculate the standard deviation with bootstrapping (sd) and the associated standard error in 30 scan windows. The function below performs the corresponding rolling window if I just want sd. But when I add the bootstrap function using the boot package, I get the error below. I understand that I am trying to save the results of the bootstrap into a vector that does not fit the size. Does anyone have any tips on how to store only the boot sd and related stderror for each window in the rows of the new matrix? The goal is then to build sd and the corresponding 95% confidence intervals for each window over time. Thanks in advance for any help.

> 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
source share
1 answer

You can simplify it quite a lot. I am not familiar with the boot package, but we can easily roll a function in a vector using the rollapply function, and then we can create bootstraps using the replicate function:

 # 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 

Each column is rollapply, which loads the observations in the current window before applying sd .

+1
source

All Articles