Displaying 1 result from an estimated 1 matches for "lag_by".
Did you mean:
lag_1
2007 Dec 13
1
creating lagged variables
...effort produced the following:
##
my_lag <- function(dt, varname, timevarname='time', lag=1) {
vname <- paste(varname, if(lag>0) '.' else '', lag, sep='')
timevar <- dt[[timevarname]]
dt[[vname]] <- dt[[varname]][match(timevar, timevar + lag)]
dt
}
lag_by <- function(dt, idvarname='id', ...)
do.call(rbind, by(dt, dt[[idvarname]], my_lag, ...))
##
With the previous data I get:
> lag_by(d, varname='value')
id time value value.1
1.1 1 1 -0.56047565 NA
1.2 1 2 -0.23017749 -0.56047565
1.3 1 3 1...