Displaying 1 result from an estimated 1 matches for "idvarname".
2007 Dec 13
1
creating lagged variables
...ing:
##
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.55870831 -0.23017749
2.4 2...