1
votes

I have several merged daily zoo timeseries (let's say the name of the merged set is 'test') that appear in the following format:

>test 


              TS1     TS2     TS3
2014-07-30    2.0     3.0     4.0
2014-07-31    2.5     3.0     4.5
2014-08-01    3.0     3.0     5.0

I am wanting to aggregate/manipulate the time series in several ways. However, the simplest averaging or suming is escaping me. I tried the following:

ts <- apply.daily(as.xts(test),mean)

which I had thought would give me the following output:

>ts

                  X    
    2014-07-30    3.0     
    2014-07-31    3.3     
    2014-08-01    3.7    

However, it returns the same time series as before. I understand that this would be useful for apply.weekly() and apply.monthly(), both of which I plan to use, but how can I adapt all these functions to wrap TS1, TS2, and TS3 into an overall average on the same basis, whilst maintaining the zoo/xts formatting.

Many thanks

1

1 Answers

2
votes

Based on the example showed, we can concatenate the rows and take the mean

apply.daily(as.xts(test), function(x) round(mean(c(x)),1))
#          [,1]
#2014-07-30  3.0
#2014-07-31  3.3
#2014-08-01  3.7

Note that using the OP's code on a daily dataset returns the input data as there is only a single observation for the criteria. Suppose if the dataset is datetime class, then using apply.daily will return the mean for each single day, wrap it up with another mean to get the mean for each row, i.e.

test1 <- structure(list(TS1 = c(2, 2.5, 3, 2.2), TS2 = c(3, 3, 3, 3.2), 
TS3 = c(4, 4.5, 5, 4.4)), .Names = c("TS1", "TS2", "TS3"), 
 class = "data.frame", row.names = c("2014-07-30 07:00:00", 
"2014-07-31 05:00:00", "2014-08-01 03:00:00", "2014-07-30 07:20:00"))

apply.daily(as.xts(test1), function(x) round(mean(mean(x)),1))
#                   [,1]
#2014-07-30 07:20:00  3.1
#2014-07-31 05:00:00  3.3
#2014-08-01 03:00:00  3.7

As we are using anonymous function, we don't need the two mean

 apply.daily(as.xts(test1), function(x) round(mean(x),1))
 #                     [,1]
 #2014-07-30 07:20:00  3.1
 #2014-07-31 05:00:00  3.3
 #2014-08-01 03:00:00  3.7

Checking the above results with OP's approach

apply.daily(as.xts(test1), mean)
#                   TS1 TS2 TS3
#2014-07-30 07:20:00 2.1 3.1 4.2
#2014-07-31 05:00:00 2.5 3.0 4.5
#2014-08-01 03:00:00 3.0 3.0 5.0

round(mean(c(2.1, 3.1, 4.2)), 1)
#[1] 3.1
round(mean(c(2.5, 3.0, 4.5)), 1)
#[1] 3.3