Skip to main content

Slide: one function for lag/lead variables in data frames, including time-series cross-sectional data

I often want to quickly create a lag or lead variable in an R data frame. Sometimes I also want to create the lag or lead variable for different groups in a data frame, for example, if I want to lag GDP for each country in a data frame.

I've found the various R methods for doing this hard to remember and usually need to look at old blog posts. Any time we find ourselves using the same series of codes over and over, it's probably time to put them into a function.

So, I added a new command–slide–to the DataCombine R package (v0.1.5).

Building on the shift function TszKin Julian posted on his blog, slide allows you to slide a variable up by any time unit to create a lead or down to create a lag. It returns the lag/lead variable to a new column in your data frame. It works with both data that has one observed unit and with time-series cross-sectional data.

Note: your data needs to be in ascending time order with equally spaced time increments. For example 1995, 1996, 1997.


Examples

Not Cross-sectional data

Let's create an example data set with three variables:

# Create time variable
Year <- 1980:1999

# Dummy covariates
A <- B <- 1:20

Data1 <- data.frame(Year, A, B)

head(Data1)
##   Year A B
## 1 1980 1 1
## 2 1981 2 2
## 3 1982 3 3
## 4 1983 4 4
## 5 1984 5 5
## 6 1985 6 6

Now let's lag the A variable by one time unit.

library(DataCombine)

DataSlid1 <- slide(Data1, Var = "A", slideBy = -1)

head(DataSlid1)
##   Year A B A-1
## 1 1980 1 1  NA
## 2 1981 2 2   1
## 3 1982 3 3   2
## 4 1983 4 4   3
## 5 1984 5 5   4
## 6 1985 6 6   5

The lag variable is automatically given the name A-1.

To lag a variable (i.e. the lag value at a given time is the value of the non-lagged variable at a time in the past) set the slideBy argument as a negative number. Lead variables, are created by using positive numbers in slideBy. Lead variables at a given time have the value of the non-lead variable from some time in the future.

Time-series Cross-sectional data

Now let's use slide to create a lead variable with time-series cross-sectional data. First create the example data:

# Create time and unit ID variables
Year <- rep(1980:1983, 5)
ID <- sort(rep(seq(1:5), 4))

# Dummy covariates
A <- B <- 1:20

Data2 <- data.frame(Year, ID, A, B)

head(Data2)
##   Year ID A B
## 1 1980  1 1 1
## 2 1981  1 2 2
## 3 1982  1 3 3
## 4 1983  1 4 4
## 5 1980  2 5 5
## 6 1981  2 6 6

Now let's create a two time unit lead variable based on B for each unit identified by ID:

DataSlid2 <- slide(Data2, Var = "B", GroupVar = "ID",
                    slideBy = 2)

head(DataSlid2)
##   Year ID A B B2
## 1 1980  1 1 1  3
## 2 1981  1 2 2  4
## 3 1982  1 3 3 NA
## 4 1983  1 4 4 NA
## 5 1980  2 5 5  7
## 6 1981  2 6 6  8

Hopefully you'll find slide useful in your own data analysis. Any suggestions for improvement are always welcome.

Comments

Tilly Tan said…
in your last exmample, what if i want to have the first 3 vairble in each group to have a lag value of 2, how can i do it?

Cheers,
Tilly
tttilly@gmail.com
Tilly, do you mean lag the A and B variables by 2? Or do you mean lag the first three rows for each group by 2?
Highgamma said…
Cool. I can use this to create returns for any time lag.
is this faster than using plyr as is what I'm currently using? plyr is beautiful but incredibly slow at times.

Sebastian for lags/leads with time- series cross-sectional data it will probably be as fast as plyr because it relies on ddply.

There might be a way to have slide use data.table rather than plyr. data.table is usually faster. I'll look into it. Thanks for the comment.
I'm using lagpanel() in the {simcf} package which makes sure that the panel structure is taken into account. Works perfectly! The package is described here: http://faculty.washington.edu/cadolph/?page=60
@politicalsciencereplication Thanks for the info. lagepanel looks pretty interesting. I like how it doesn't rely on ddply. Not sure if it does lead variables and has possibly less intuitive syntax for new users wanting to lag a variable in an existing data frame and return the new variable to the old data frame.

You've got a great blog by the way.
Fr. said…
I have submitted a fix that should make the function as quick as possible with plyr. On my training data, it is now as quick as lagpanel (which cannot do lead variables).
Thanks Fr. I just merged it in and the new version of DataCombine should be on CRAN shortly.
Danilo said…
This is by far the easiest function to lag and lead variables that I've seen. It works wonders! Thanks for lowering R's entry costs for newbies like me. :)
Thanks Danilo. Really glad that you found it useful.
homo-loquens said…
Thanks very much for this package! I am using your slide function with fairly ordinary Time-series Cross-country dataset. When I use SlideBy=-1 (or SlideBy=1) it works fine, but when I put, say, SlideBy=-2 (or SlideBy=2) I get the following error:

Error in `[<-.data.frame`(`*tmp*`, , NewVar, value = c(NA, NA, NA, NA, :
replacement has 4098 rows, data has 4097

What do you think could cause this problem?
Hi homo-loquens

First of all, can you run the examples in the slide documentation ok?

If so then there might be some issue with your grouping or time variables. Not exactly sure without seeing the data.
homo-loquens said…
Thank you, I think I have figured it out for the time being. Would post further if necessary.

Popular posts from this blog

Do Political Scientists Care About Effect Sizes: Replication and Type M Errors

Reproducibility has come a long way in political science. Many major journals now require replication materials be made available either on their websites or some service such as the Dataverse Network. Most of the top journals in political science have formally committed to reproducible research best practices by signing up to the The (DA-RT) Data Access and Research Transparency Joint Statement.This is certainly progress. But what are political scientists actually supposed to do with this new information? Data and code availability does help avoid effort duplication--researchers don't need to gather data or program statistical procedures that have already been gathered or programmed. It promotes better research habits. It definitely provides ''procedural oversight''. We would be highly suspect of results from authors that were unable or unwilling to produce their code/data.However, there are lots of problems that data/code availability requirements do not address.…

Showing results from Cox Proportional Hazard Models in R with simPH

Update 2 February 2014: A new version of simPH (Version 1.0) will soon be available for download from CRAN. It allows you to plot using points, ribbons, and (new) lines. See the updated package description paper for examples. Note that the ribbons argument will no longer work as in the examples below. Please use type = 'ribbons' (or 'points' or 'lines'). Effectively showing estimates and uncertainty from Cox Proportional Hazard (PH) models, especially for interactive and non-linear effects, can be challenging with currently available software. So, researchers often just simply display a results table. These are pretty useless for Cox PH models. It is difficult to decipher a simple linear variable’s estimated effect and basically impossible to understand time interactions, interactions between variables, and nonlinear effects without the reader further calculating quantities of interest for a variety of fitted values.So, I’ve been putting together the simPH R p…