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

落爺英雄遲暮 提交于 2019-11-29 05:06:23

问题


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.


回答1:


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, ...)
}



回答2:


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

This should work fine.




回答3:


Answering part 2:

What if I want to aggregate the mean of 5 minutes?

As @eddit already mentioned in a comment above:

df <- read.table(header=TRUE, sep=",", stringsAsFactors=FALSE, text="
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")
X2 <- xts(df$value, as.POSIXct(df$timestamp))

X2.5min <- period.apply(X2, endpoints(X2, "minutes", 5), mean)

I get: 05:04:00 - 4; 05:09:00 - 5,... but maybe it is possible to set the first value to 05:00:00 and go on with 05:05:00 might be easier, if I am merging files later to have the same start and timestep.

Indeed:

> X2.5min
                    [,1]
2012-04-09 05:04:00  3.0
2012-04-09 05:09:00  1.6
2012-04-09 05:10:00  1.0

Darren Cook over at Cross Validated faced the same issue and wrote function align.time.down:

align.time.down=function(x,n){index(x)=index(x)-n;align.time(x,n)}

That can be used to adjust the times down:

X2.5mindown <- align.time.down(X2.5min, 5 * 60)
X2.5mindown
                    [,1]
2012-04-09 05:00:00  3.0
2012-04-09 05:05:00  1.6
2012-04-09 05:10:00  1.0


来源:https://stackoverflow.com/questions/16019187/why-is-there-no-apply-hourly-in-r-with-xts-zoo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!