Skip to content
Prev 75512 / 398502 Next

How to make a lagged variable in panel data?

On 8/13/05, Ila Patnaik <ila at mayin.org> wrote:
We can use 'by' to split data frame A by person and to
apply the function f to each such subset of rows. Function f
makes that portion of wage which corresponds to a single
person into a ts class time series so that we can use lag
with it and then we cbind wage together with its lag.  From
the cbind'ed result we extract out those times that
correspond to the original series since the example output
only includes those. Note that such extraction has a side
effect of turning wages into a matrix rather than a time
series.  We then put every together using cbind(...) once
again and once the 'by' is complete we rbind all rows together.

	f <- function(x) { 
		wage <- ts(x$wage, start = x$year[1])
		idx <- seq(length = length(wage))
		wages <- cbind(wage, lag(wage, -1))[idx,]
		cbind(x[,1:2], wages)
	}

	result <- do.call("rbind", by(A, A$person, f))
	result