Learn R Programming

DataCombine (version 0.1.12)

slide: A function for creating lag and lead variables, including for time-series cross-sectional data.

Description

The function slides a column up or down to create lag or lead variables. If GroupVar is specified it will slide Var for each group. This is important for time-series cross-section data. The slid data is placed in a new variable in the original data frame. Note: your data needs to be sorted by date. The date should be ascending (i.e. increasing as it moves down the rows). Also, the time difference between rows should be constant, e.g. days, months, years.

Usage

slide(data, Var, GroupVar = NULL, NewVar = NULL, slideBy = -1)

Arguments

Value

  • a data frame

source

Partially based on TszKin Julian's shift function: http://ctszkin.com/2012/03/11/generating-a-laglead-variables/

Details

slide a function for creating lag and lead variables, including for time-series cross-sectional data.

See Also

shift, ddply

Examples

Run this code
# Create dummy data
 A <- B <- C <- 1:20
 ID <- sort(rep(seq(1:4), 5))
 Data <- data.frame(ID, A, B, C)

 # Lead the variable by two time units
 DataSlid1 <- slide(Data, Var = "A", NewVar = "ALag", slideBy = 2)

 # Lag the variable one time unit by ID group
 DataSlid2 <- slide(data = Data, Var = "B", GroupVar = "ID",
                NewVar = "BLag", slideBy = -1)

Run the code above in your browser using DataLab