Here's some data:
> x <- zoo(matrix(1:12, 4, 3), as.Date("2003-01-01") + 0:3)
> x
2003-01-01 1 5 9
2003-01-02 2 6 10
2003-01-03 3 7 11
2003-01-04 4 8 12
If you want to lag this multivariate time series, just call lag (i.e. no need for apply):
> lag(x)
2003-01-01 2 6 10
2003-01-02 3 7 11
2003-01-03 4 8 12
If you want to apply a function across the rows, it needs to be sensible. For instance, to get mean of the row values:
> apply(x, 1, mean)
2003-01-01 2003-01-02 2003-01-03 2003-01-04
5 6 7 8
You can't apply a zoo object and get a zoo object back. The output of apply is "a vector or array or list of values". In the example above:
> class(apply(x, 1, mean))
[1] "numeric"
You need to recreate it as a zoo object and then lag it:
> lag(zoo(apply(coredata(x), 1, mean), index(x)))
2003-01-01 2003-01-02 2003-01-03
6 7 8
You need to be slightly careful of the direction of your output. But you can transpose it if necessary with the t()
function. For instance:
> zoo(t(apply(coredata(x), 1, quantile)), index(x))
0% 25% 50% 75% 100%
2003-01-01 1 3 5 7 9
2003-01-02 2 4 6 8 10
2003-01-03 3 5 7 9 11
2003-01-04 4 6 8 10 12
You could also wrap this in a function. Alternatively you can use one of the apply functions in the xts
time series library (this will retain the time series object in the process):
> x <- as.xts(x)
> apply.daily(x, mean)
[,1]
2003-01-01 5
2003-01-02 6
2003-01-03 7
2003-01-04 8