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.


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)

##   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.


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

##   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)

##   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)

##   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.


Unknown 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?

Unknown said…
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.

Unknown said…
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.
Anonymous said…
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:
Unknown said…
@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).
Unknown said…
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. :)
Unknown said…
Thanks Danilo. Really glad that you found it useful.
Anonymous 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 `[<`(`*tmp*`, , NewVar, value = c(NA, NA, NA, NA, :
replacement has 4098 rows, data has 4097

What do you think could cause this problem?
Unknown said…
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.
Anonymous said…
Thank you, I think I have figured it out for the time being. Would post further if necessary.
Unknown said…
There are lots of data scientist are here for solving your all type of data related problems, but the selecting of best data scientist from the variety of different scientist is also a big problem for us because we need the best data solution provide on very cheap rate. So this can help you better to find the best and cheap data scientist for your work.
Unknown said…
Hi Christopher
I really like your slide function! However, I'm getting kind of annoyed about the naming of lag variables where the "-" confuses other functions. Could this possibly be changed into some other naming such as lagivar where i is the lag number and var is the variable name?
Best, Christoffer
When I use slide to construct lagged x, the resulting variable is x-1. When I try to use the dataframe in other functions this name does not work. I could not find to rename it either. Please help.
Unknown said…
Very interesting blog post.Quite informative and very helpful.This indeed is one of the recommended blog for learners.Thank you for providing such nice piece of article. I'm glad to leave a comment. Expect more articles in future. You too can check this R Programming tutorial for updated knowledge on R Programming.
Unknown said…

Worthful Data Science tutorial. Appreciate a lot for taking up the pain to write such a quality content on Data Science course. Just now I watched this similar Data Science tutorial and I think this will enhance the knowledge of other visitors for sure. Thanks anyway.:-
nikitha josh said…
I have gone through your blog, it was very much useful for me and because of your blog, and also I gained many unknown information, the way you have clearly explained is really fantastic. Kindly post more like this, Thank You.
best aviation academy in chennai
cabin crew course in chennai
diploma in airport management course in chennai
airport ground staff training in chennai
medical coding classes in Chennai
Fashion designing courses in Chennai
best interior design courses in chennai

shivani said…
A bewildering web journal I visit this blog, it's unfathomably heavenly. Oddly, in this present blog's substance made the purpose of actuality and reasonable. The substance of data is informative
Oracle Fusion Financials Online Training
Oracle Fusion HCM Online Training
Oracle Fusion SCM Online Training
anusha said…

MEAN Stack Training in Chennai MEAN Stack Training in Chennai with real time projects. We are Best MEAN Stack Training Institute in Chennai. Our Mean Stack courses are taught by Industrial Experts which would help you to learn MEAN Stack development from the scratch.
basha said…
Excellent blog I visit this blog it's really awesome. The important thing is that in this blog content written clearly and understandable. The content of information is very informative.
Magnificent blog I visit this blog it's extremely wonderful. Interestingly, in this blog content composed plainly and reasonable. The substance of data is useful.
Oracle Fusion HCM Online Training
Oracle Fusion SCM Online Training
Oracle Fusion Financials Online Training
Big Data and Hadoop Training In Hyderabad
oracle fusion financials classroom training
Oracle Fusion HCM Classroom Training
oracle cpq online training / Oracle CPQ Class Room Training
Oracle Taleo Online Training
shivani said…
A befuddling web diary I visit this blog, it's incredibly grand. Strangely, in this present blog's substance made motivation behind fact and sensible. The substance of information is instructive
Oracle Fusion Financials Online Training
Oracle Fusion HCM Online Training
Oracle Fusion SCM Online Training
Tiffany said…
If you're looking for a date but not sure whether the dating site is a safe place, check our review.
Komal said…
nice information on data science has given thank you very much.
Data Science coaching in Hyderabad
your article on data science is very interesting thank you so much.
Data Science coaching in Hyderabad
Jhon Michael said…
Red Hat Certified Engineer is a professional who has expertise in handling the Red Hat Enterprise Linux System. The Certified Engineer takes care of various tasks such as setting kernel runtime parameters, handling various types of system logging and providing certain kinds of network operability. The professionals must have the ability to install networking services and security on servers running Red Hat Enterprise Linux.

Red Hat Certified Engineer
Thanks for provide great informatic and looking beautiful blog, really nice required information & the things i never imagined and i would request, wright more blog and blog post like that for us. Thanks you once agian
we offer services delhi birth certificate which inculde name add in birth certificate and birth certificate correction complete process is online and we offer
birth certificate and we offer this birth certificate online same service offers at yourdoorstep at birth certificate in ghaziabad our dream to provide birth certificate in india and other staes like birth certificate in bengaluru and birth certificate in gurgaon book service with us birth certificate in noida also, service at yoursdoorstep only birth certificate in india or
I was very happy to find this site. I really enjoyed reading this article today and think it might be one of the best articles I have read so far. I wanted to thank you for this excellent reading !! I really enjoy every part and have bookmarked you to see the new things you post. Well done for this excellent article. Please keep this work of the same quality.
Data Science Course in Bangalore
Rohan Singh said…
You rocked in this post; we are also work in the same field. Being one of the most trusted mobile app development company we are looking forward to serving clients with superb IT solutions. Also visit: kotlin app development company
Fantastic Site with relevant information and content Shared was knowledgeable thank you.
Data Science Course in Hyderabad
Shanmugam said…
Thanks for sharing this wonderful information. I too learn something new from your post..
Mean Stack Training in Chennai
diana said…

Thank you so much for the sharing, it was so informative and I read all your blogs that's so nice and informative.
interior designers in chennai
interiors in chennai
best builders in chennai
Construction companies in chennai
senthilr7692 said…
This blog has the relevant data according to the topic and precise to the topic.
Data Science Course in Chennai
Data Science Course in Bangalore

Popular posts from this blog

A Link Between topicmodels LDA and LDAvis

Carson Sievert and Kenny Shirley have put together the really nice LDAvis R package. It provides a Shiny-based interactive interface for exploring the output from Latent Dirichlet Allocation topic models. If you've never used it, I highly recommend checking out their XKCD example (this paper also has some nice background). LDAvis doesn't fit topic models, it just visualises the output. As such it is agnostic about what package you use to fit your LDA topic model. They have a useful example of how to use output from the lda package. I wanted to use LDAvis with output from the topicmodels package. It works really nicely with texts preprocessed using the tm package. The trick is extracting the information LDAvis requires from the model and placing it into a specifically structured JSON formatted object. To make the conversion from topicmodels output to LDAvis JSON input easier, I created a linking function called topicmodels_json_ldavis . The full function is below. To

Set up R/Stan on Amazon EC2

A few months ago I posted the script that I use to set up my R/JAGS working environment on an Amazon EC2 instance. Since then I've largely transitioned to using R/ Stan to estimate my models. So, I've updated my setup script (see below). There are a few other changes: I don't install/use RStudio on Amazon EC2. Instead, I just use R from the terminal. Don't get me wrong, I love RStudio. But since what I'm doing on EC2 is just running simulations (I handle the results on my local machine), RStudio is overkill. I don't install git anymore. Instead I use source_url (from devtools) and source_data (from repmis) to source scripts from GitHub. Again all of the manipulation I'm doing to these scripts is on my local machine.