Search code examples
rgroup-bytime-seriesxts

How to group by time for XTS object in R?


I have this a time series xts object in R.

Basically the time series duration is a few months, I want to know the trend for different time points.

I want to get the median or mean for different time points.

library(xts)
library(lubridate)
Time <- seq(ymd_hms("2019-01-01 00:00:00"), ymd_hms("2019-03-29 23:59:59"), "hour")
length(Time)
Data <- rnorm(2112, 1, 5)
Time_Series <- xts(x = Data , order.by = Time)

Take this code as example.

How can I get the mean for the data at time 00:00:00? similarly the mean of data in 01:00:00, 02:00:00, 03:00:00 ...

Thank you for your helping in advance!


Solution

  • This one-liner uses aggregate.zoo producing a zoo object whose time is the hour. No additional packages are used.

    aggregate(Time_Series, hour, mean)
    

    giving:

    0  0.4237426
    1  1.8814963
    2  1.2917437
    3  1.4307028
    4  1.3691019
    5  0.3762082
    6  1.3866948
    # ...snip...
    

    Note that the data in the question is not reproducible since set.seed was not used so this just shows what the output looks like.