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
Cheers,
Tilly
tttilly@gmail.com
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.
You've got a great blog by the way.
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?
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.
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
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.:-https://www.youtube.com/watch?v=gXb9ZKwx29U&t=237s
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.
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
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
vé máy bay đi Mỹ
vé máy bay tết 2021 pacific airlines
vé máy bay đi Canada bao nhiêu tiền
vé máy bay đi Pháp giá rẻ 2021
vé máy bay khứ hồi đi Anh
vé máy bay giá rẻ 99k
combo trọn gói đà lạt
combo nha trang 4 ngày 3 đêm 2021
visa trung quốc phùng chí kiên
giá vé máy bay đi Mỹ khứ hồi
vé máy bay bmt đi hà nội
vé máy bay hn sài gòn
vé máy bay đi nha trang tháng 7
chuyến bay mỹ về việt nam
taxi sân bay hà nội giá rẻ
combo anantara quy nhơn
Mean Stack Training in Chennai
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
vé máy bay đi Mỹ hạng thương gia
đặt vé máy bay hồ chí minh hà nội
vé máy bay quy nhơn sg
vé máy bay hanoi nha trang
đăng ký về việt nam ở mỹ
taxi sân bay rẻ nhất
bamboo airways combo quy nhơn
AI Training in Hyderabad
Artificial Intelligence In Industry
Application Areas Of Artificial Intelligence
Types of digital marketing
What is Digital Marketing?
Data Analytics Course in Chennai
mobile app development services
android app development on mobile
ios app development services
react native app development
ionic app development company
flutter app development company
angularjs web development
would like to show my appreciation to the writer for rescuing me from this type of situation. After looking through the the net and seeing methods which were not pleasant, I figured my life was over. Living minus the answers to the problems you’ve sorted out by way of your entire short article is a crucial case, and those that might have adversely affected my entire career if I hadn’t come across your web site. Your actual capability and kindness in maneuvering all the pieces was vital. I don’t know what I would have done if I had not come upon such a stuff like this. I can at this time look ahead to my future. Thanks for your time very much for this high quality and results-oriented guide. I won’t hesitate to refer your site to anyone who requires counselling about this issue.
My wife and i ended up being so fortunate that Jordan managed to deal with his inquiry out of the precious recommendations he was given out of the blog. It’s not at all simplistic just to find yourself giving away tactics which often a number of people have been trying to sell. And we realize we’ve got the writer to be grateful to because of that. All of the explanations you made, the easy website menu, the friendships your site help engender – it’s got most fabulous, and it’s really aiding our son in addition to the family understand the topic is enjoyable, and that’s really pressing. Thank you for the whole lot!
how to lose facial fat
Solicitation Of A Minor VA
Online Solicitation Of A Minor
abogado de testamentos y sucesiones cerca de mí
Divorce Lawyers Culpeper VA
Divorce Lawyers Northern VA
Divorce Lawyers Fredericksburg VA
https://srislawyer.com/divorce-lawyers-stafford-spotsylvania-fredericksburg-culpeper-orange-va/
văn phòng china airlines
phòng vé china airlines hồ chí minh
văn phòng eva air
đại lý EVA Air
Tổng đài EVA Air
Số điện thoại EVA Air
Regards,
BroadMind - IELTS Class in Madurai