R lagged data with time-series cross-sectional data.
If you want to create a lagged variable in R for time-series cross-sectional data the usual time series packages (i.e. zoo and xts) don't really do the job.
So use the plyr package.
Imagine we have a data frame (Data) with three variables: Country, Year and Variable. We want to lag Variable one year for each country. Let's call the lagged variable VariableLag1. Use the ddply command like this:
library(plyr)
Data <- ddply(Data, .(country), transform, VariableLag1 =
c(NA, Variable[-length(Variable)]
)
)
That's it.
Thanks to this post on StackOverflow.
Written by Christopher Gandrud
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#R
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#