lagit: Apply a lag to a _numeric_ or _Boolean_ vector, matrix, or...

View source: R/rutils.R

lagitR Documentation

Apply a lag to a numeric or Boolean vector, matrix, or xts time series.

Description

Apply a lag to a numeric or Boolean vector, matrix, or xts time series.

Usage

lagit(input, lagg = 1, pad_zeros = TRUE, ...)

Arguments

input

A numeric or Boolean vector or matrix, or xts time series.

lagg

An integer equal to the number of time periods (rows) of lag (default is 1).

pad_zeros

A Boolean argument: Should the output be padded with zeros? (The default is pad_zeros = TRUE.)

Details

The function lagit() applies a lag to the input object by shifting its rows by the number of time periods equal to the integer argument lagg.

For positive lagg values, the current row is replaced with the row that is lagg rows above it. And vice versa for a negative lagg values. This also applies to vectors, since they can be viewed as single-column matrices. If lagg = 0, then lagit() returns the input object unchanged.

To avoid leading or trailing NA values, the output object is padded with zeroes, or with elements from either the first or the last row.

For the lag of asset returns, they should be padded with zeros, to avoid look-ahead bias. For the lag of prices, they should be padded with the first or last prices, not with zeros.

When applied to xts time series, the function lagit() calls the function lag.xts() from package xts, but it pads the output with the first and last rows, instead of with NAs.

Value

A vector, matrix, or xts time series. with the same dimensions as the input object.

Examples

# Lag vector by 2 periods
rutils::lagit(1:10, lag=2)
# Lag matrix by negative 2 periods
rutils::lagit(matrix(1:10, ncol=2), lag=-2)
# Lag an xts time series
lag_ged <- rutils::lagit(rutils::etfenv$VTI, lag=10)

algoquant/rutils documentation built on April 18, 2024, 12:05 a.m.