Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R bootstrap time series

I would like to generate four bootstrap samples from a time series data set and have each new bootstrapped sample become a new list element. The sample size needs to be the same length as the original data set. Can someone please give me a hand? This is all I could come up with so far.

data <- ts(matrix(rnorm(36), 12, 3), start=c(2012, 1), frequency=12)
data
replicate(4, apply(data, 1, sample, replace=TRUE))
like image 552
user1491868 Avatar asked Mar 21 '26 01:03

user1491868


1 Answers

You were nearly there. Your description wasn't totally clear at first, but the comment cleared it up. You need to apply across columns, and use list to make each replicate a list element:

boot <- replicate( 4 , list( apply(data , 2 , function(x) sample( x , replace=TRUE ) ) ) )

class(boot)
#[1] "list"

length( boot )
#[1] 4

head(boot[[1]])

#       Series 1    Series 2   Series 3
#[1,]  0.4652513 -0.02065698  0.3328945
#[2,]  0.6649865  0.08845410  0.2032134
#[3,]  0.5975473 -1.64571306  1.6516726
#[4,]  0.5975473 -0.23359075 -0.3255437
#[5,]  0.4008458  0.42180633  1.8402009
#[6,] -0.5436319  1.17034910  0.3456304

EDIT

Since you need to do whole rows at a time this is even easier!

boot <- replicate( 4 , list( data[ sample( nrow(data) , replace = TRUE ) , ] ) )
like image 92
Simon O'Hanlon Avatar answered Mar 22 '26 14:03

Simon O'Hanlon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!