lagdf: Lagging which returns a data.frame

View source: R/lagdf.R

lagdfR Documentation

Lagging which returns a data.frame

Description

Lagging by shifting the values back or fourth always returning a data.frame.

Lagging of a data.frame

Usage

lagdf(x, lagseq)

## S3 method for class 'data.frame'
lagdf(x, lagseq)

Arguments

x

The data.frame to have columns lagged

lagseq

The sequence of lags as an integer. Alternatively, as a character "+k", "-k", "+h" or "-h", e.g. "k12" will with "+k" be lagged 12.

Details

This function lags (shifts) the values of the vector. A data.frame is always returned with the columns as the vectors lagged with the values in lagseq. The column names are set to "kxx", where xx are the lag of the column.

This function lags the columns with the integer values specified with the argument lagseq.

Value

A data.frame.

A data.frame with columns that are lagged

See Also

lagdf.data.frame which is run when x is a data.frame.

Examples

# The values are simply shifted
# Ahead in time
lagdf(1:10, 3)
# Back in time
lagdf(1:10, -3)
# Works but returns a numeric column
lagdf(as.factor(1:10), 3)
# Works and returns a character column
lagdf(as.character(1:10), 3)
# Giving several lag values
lagdf(1:10, c(1:3))
lagdf(1:10, c(5,3,-1))

# See also how to lag a forecast data.frame with: ?lagdf.data.frame



# dataframe of forecasts
X <- data.frame(k1=1:10, k2=1:10, k3=1:10)
X

# Lag all columns
lagdf(X, 1)


# Lag each column different steps
lagdf(X, 1:3)
# Lag each columns with its k value from the column name
lagdf(X, "+k")

# Also works for columns named hxx
names(X) <- gsub("k", "h", names(X))
lagdf(X, "-h")

# If lagseq must have length as columns in X, it doesn't know how to lag and an error is thrown
try(lagdf(X, 1:2))




onlineforecast documentation built on Oct. 12, 2023, 5:15 p.m.