
Last chance! 50% off unlimited learning
Sale ends in
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.
slide(data, Var, TimeVar, GroupVar, NewVar, slideBy = -1, keepInvalid = FALSE, reminder = TRUE)
Var
will be slid. If GroupVar
is missing then the
whole variable is slid up or down. This is similar to shift
,
though shift
returns the slid data to a new vector rather than the
original data frame.TRUE
then these groups are returned to the
bottom of the data frame and NA
is given for their new lag/lead
variable value.GroupVar
and time variable before running slide
, plus other
messages.shift
function:
http://ctszkin.com/2012/03/11/generating-a-laglead-variables/slide
a function for creating lag and lead variables, including for
time-series cross-sectional data.
shift
, dplyr
# Create dummy data
A <- B <- C <- sample(1:20, size = 20, replace = TRUE)
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 = 'ALead', slideBy = 2)
# Lag the variable one time unit by ID group
DataSlid2 <- slide(data = Data, Var = 'B', GroupVar = 'ID',
NewVar = 'BLag', slideBy = -1)
# Lag the variable one time unit by ID group, with invalid lags
Data <- Data[1:16, ]
DataSlid3 <- slide(data = Data, Var = 'B', GroupVar = 'ID',
NewVar = 'BLag', slideBy = -2, keepInvalid = TRUE)
Run the code above in your browser using DataLab