Learn R Programming

gfunctions (version 1.1)

glag: Lag a vector or a matrix, with special treatment of zoo and ts objects

Description

The glag() function is similar to the lag() function from the stats package, but glag() actually lags (the default in lag() is to lead). The funtion glag() also enables padding (for example NAs or 0s) of the lost entries. Contrary to the lag() function, however, the default in glag() is to pad (with NAs). The glag() is particularly suited for zoo objects, since their indexing is retained. The prefix g is a reminder of who to blame if things do not work properly.

Usage

## generic:
glag(x, ...)
# S3 method for default
glag(x, k = 1, pad = TRUE, pad.value = NA, ...)

Value

A vector or matrix, or objects of class zoo or ts, with the lagged values.

Arguments

x

a numeric vector or matrix, or objects of class zoo or ts.

k

integer equal to the lag (the default is 1). Negative values (that is, 'leading') is not possible.

pad

logical. If TRUE (default), then the lost entries are padded with pad.value. If FALSE, then no padding is undertaken.

pad.value

the padding value.

...

additional arguments

Author

Genaro Sucarrat, https://www.sucarrat.net/

See Also

Examples

Run this code
##generate some data:
x <- rnorm(5)

##lag series with NAs on missing entries:
glag(x)

##lag series with no padding:
x <- rnorm(5)
glag(x, pad = FALSE)

##lag series and retain the original zoo-index ordering:
x <- as.zoo(rnorm(5))
glag(x)

##lag two periods:
glag(x, k = 2)

Run the code above in your browser using DataLab