Search code examples
rxts

Find the mean of multiple observations in an extensible time series


I have an xts with multiple performances on a specific date:

                    Performance
2004-05-31        -7.478589e-03
2004-06-30         1.565250e-02
2004-06-30         1.372764e-02
2004-07-30        -1.558922e-03
2004-07-30        -1.451943e-02
2004-07-30        -3.829991e-02
2004-08-31        -4.456728e-03
2004-08-31        -1.547637e-03
2004-08-31         1.901513e-02

I would like to get a new time series or dataframe, does not really matter, with the means of every date index:

                    Performance
2004-05-31        -7.478589e-03
2004-06-30         1.469007e-02 (mean of both 2004-06-30 observations)
2004-07-30        -5.225589e-03 (mean of three 2004-07-30 observations)
... 

I have looked through the xts cheat sheat and the interwebs and have found nothing similar. Does anybody have an idea what function i could use? Thank you very much for your time.


Solution

  • One option is to group by the index in tapply and get the mean

    tapply(xt1, index(xt1), FUN = mean)
    #  2004-05-31   2004-06-30   2004-07-30   2004-08-31 
    #-0.007478589  0.014690070 -0.018126087  0.004336922 
    

    Or with apply.daily

    library(xts)
    apply.daily(xt1, mean)
    #              [,1]
    #2004-05-31 -0.007478589
    #2004-06-30  0.014690070
    #2004-07-30 -0.018126087
    #2004-08-31  0.004336922
    

    data

    xt1 <- structure(c(-0.007478589, 0.0156525, 0.01372764, -0.001558922, 
    -0.01451943, -0.03829991, -0.004456728, -0.001547637, 0.01901513
    ), .Dim = c(9L, 1L), index = structure(c(1085961600, 1088553600, 
    1088553600, 1091145600, 1091145600, 1091145600, 1093910400, 1093910400, 
    1093910400), tzone = "UTC", tclass = "Date"), class = c("xts", 
    "zoo"), .indexCLASS = "Date", tclass = "Date", .indexTZ = "UTC", tzone = "UTC")