[R] Lags and Differences of zoo Objects
Gabor Grothendieck
ggrothendieck at gmail.com
Sat Jul 31 06:49:33 CEST 2010
On Sat, Jul 31, 2010 at 12:07 AM, pdb <philb at philbrierley.com> wrote:
>
> Hi,
>
> I'm struggling to understand the documentation.
>
> ?lag.zoo
>
>
> x - a "zoo" object.
> k, lag - the number of lags (in units of observations). Note the sign of k
> behaves as in lag.
> differences - an integer indicating the order of the difference.
>
> What does the above line actually mean? I've tried a few settings on sample
> data but can't figure out what it is doing.
>
>
> x <- iris
> x$Species = NULL
> x$Petal.Width = NULL
> x$Sepal.Width = NULL
> x$Sepal.Length = NULL
>
> x <- zoo(x)
>
> x <-
> merge(orig = x
> ,lag1diff2 = diff(x, lag = 1, differences = 2, arithmetic = TRUE, na.pad =
> TRUE)
> ,lag2diff1 = diff(x, lag = 2, differences = 1, arithmetic = TRUE, na.pad =
> TRUE)
> ,lag2diff2 = diff(x, lag = 2, differences = 2, arithmetic = TRUE, na.pad =
> TRUE)
> )
>
> head(x)
>
It works the same as lag in the core of R. See ?lag where it says that
a series lagged by a positive lag will start earlier. For example,
lagz starts at -1 which is 2 units earlier than the start of z.
> library(zoo)
> z <- zooreg(11:15)
> merge(z, zlag = lag(z, 2))
z zlag
-1 NA 11
0 NA 12
1 11 13
2 12 14
3 13 15
4 14 NA
5 15 NA
Note that zoo series cannot be lagged outside of the index range (but
zooreg series can) so if we do the above with a zoo series then we
get:
> zz <- zoo(11:15)
> merge(zz, zzlag = lag(zz, 2))
zz zzlag
1 11 13
2 12 14
3 13 15
4 14 NA
5 15 NA
The following two are the same:
diff(z)
z - lag(z, -1)
More information about the R-help
mailing list