Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating loops with xts

Tags:

loops

r

xts

This may sound trivial, but I want to know how to create a loop with a xts objects. For example I have :

make<-rbind(mean(x['199901']),
        mean(x['199902']),
        mean(x['199903']),
        mean(x['199904']),
        mean(x['199905']),
        mean(x['199906']))

x is an xts object and I will like to extract monthly means from this.

like image 597
user2165209 Avatar asked Jul 03 '26 02:07

user2165209


1 Answers

I think you should use period.apply, here an example to compute the mean for each month

zoo.data <- xts(rnorm(31)+10,as.Date(13514:13744,origin="1970-01-01"))
ep <- endpoints(zoo.data,'months')
period.apply(zoo.data, INDEX=ep, FUN=function(x) mean(x))

So to get this for only the 6 first months :

period.apply(zoo.data, INDEX=ep[1:6], FUN=function(x) mean(x))

there are also some wrappers of this function, like:

apply.daily(x, FUN, ...)
apply.weekly(x, FUN, ...)
apply.monthly(x, FUN, ...)
apply.quarterly(x, FUN, ...)
apply.yearly(x, FUN, ...
like image 123
agstudy Avatar answered Jul 04 '26 18:07

agstudy



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!