shift from
data.table does better since data.table 1.9.6.
Shifts the values of a variable forwards or
backwards to create lag or lead values. Takes a copy of the whole data
and returns a new copy with the shifted variable.
shift.var(data, id.vars = NULL, shift.var = NULL, value.vars = NULL, shift.value = -1L)data.frame or data.tableid.vars are used to identify unique subjects,
for which shifting is done separately; e.g. with a panel data where region refers to different regions that
all have their own time series, using id.vars = "region" shifts the time series for each region separatelyvalue.vars
are shifted; e.g. id.vars = "year" means shifting forward or backward in years (given one has a var name "year")shift.value = -1L shifts
one row backwards (a lag of one row) and shift.value = 2L creates a two-row lead