Last active
April 13, 2017 11:44
-
-
Save jebyrnes/5271401 to your computer and use it in GitHub Desktop.
Methods for generating lagged variables in R
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ###### | |
| # Here are some methods to create a variable | |
| # lagged at t-1. You can see some obvious ways to | |
| # generate arbitrary lags. | |
| # | |
| # See also http://ctszkin.com/2012/03/11/generating-a-laglead-variables/ | |
| # for some more tricks. | |
| # | |
| # I wonder why there is no generic function in base for this? | |
| # | |
| # by Jarrett Byrnes, 3/29/2013 | |
| ###### | |
| #If you have time flowing in only one direction | |
| # (i.e., you do not have multiple measurements per time point) | |
| adf1 <- data.frame(cbind(Time=1:10, Value=rnorm(10))) | |
| #First, resort your data frame so that the rows are in order of time | |
| #just in case it is out of order | |
| adf1 <- adf1[sort(adf1$Time, index.return=T),] | |
| #Second, use embed on the value of interest | |
| #see ?embed for more... | |
| adf1$lagValue <- c(NA, embed(adf1$Value,2)[,2]) | |
| #we can actually write a function to do this for | |
| #any data frame | |
| lag <- function(x, time_var, value_var){ | |
| x<- x[sort(x[[time_var]], index.return=T)$ix,] | |
| x$lag <- c(NA, embed(x[[value_var]],2)[,2]) | |
| x | |
| } | |
| lag(adf1, "Time", "Value") | |
| #Now, what if you have multiple measurements per time point | |
| #at multiple sites? | |
| adf <- data.frame(expand.grid(Site=c("A", "B"), Time=1:10)) | |
| adf$Value <- rnorm(nrow(adf)) | |
| #the easiest way to do this would be via plyr using the | |
| #embed technique above. | |
| library(plyr) | |
| adf <- ddply(adf, "Site", | |
| function(my_data) lag(my_data, "Time", "Value")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for the gist.
Line 20: sort(adf1$Time, index.return=T) should be sort(adf1$Time, index.return=T)$ix