Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no apply.hourly in R with xts/zoo?

I want to aggregate data by hourly mean. Daily is very easy:

apply.daily(X2,mean)

Why is there no function for hourly? I tried

hr.means <- aggregate(X2, format(X2["timestamp"],"%Y-%m-%d %H"))

and got always error with trim argument. Is there an easier function similar to apply.daily? What if I want to aggregate the mean of 5 minutes. Data are values per minute:

"timestamp", value 
"2012-04-09 05:03:00",2
"2012-04-09 05:04:00",4
"2012-04-09 05:05:00",5
"2012-04-09 05:06:00",0
"2012-04-09 05:07:00",0
"2012-04-09 05:08:00",3
"2012-04-09 05:09:00",0
"2012-04-09 05:10:00",1

I am using xts and zoo.

like image 243
Herr Student Avatar asked Apr 15 '13 15:04

Herr Student


People also ask

What is xts and zoo in R?

eXtensible Time Series (xts) is a powerful package that provides an extensible time series class, enabling uniform handling of many R time series classes by extending zoo.

What is an XTS object in R?

xts objects are simple. Think of them as a matrix of observations combined with an index of corresponding dates and times. xts = matrix + times. The main xts constructor takes a number of arguments, but the two most important are x for the data and order.by for the index. x must be a vector or matrix.


2 Answers

try

period.apply(X2, endpoints(X2, "hours"), mean)

apply.daily is simply a wrapper for the above:

> apply.daily
function (x, FUN, ...)
{
    ep <- endpoints(x, "days")
    period.apply(x, ep, FUN, ...)
}
like image 114
eddi Avatar answered Nov 10 '22 04:11

eddi


hr.means <- aggregate(X2, format(time(X2),"%y-%m-%d %H"), mean) 

This should work fine.

like image 45
athlonshi Avatar answered Nov 10 '22 05:11

athlonshi