views:

257

answers:

2

I'm trying to "apply" a function that does "lag"s on zoo objects in R.

The function works correctly if I pass a single zoo vector - it applys the lag and everything works.

However, if I "apply( data, 1, function )" then the lag doesn't work. There is no error, just the equivalent of a zero lag.

This is also the case with a simple "apply( data, 1, lag )".

Can anyone explain why this should be the case? Is there anything I can do to make the lag to occur?

A: 

@Marek - lag(data) does do what I want, but I wanted to be able to use this as part of an "apply" construct to make the vector->matrix abstraction a little easier.

Just based on everything here, I think you might benefit from more time understanding `zoo` objects, and particularly how they're different from vectors. Have you read the vignette: vignette("zoo")?
Shane
+2  A: 

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
Shane