Created
May 18, 2014 09:42
-
-
Save anonymous/0c69b019d0b4f6ae5050 to your computer and use it in GitHub Desktop.
R example of dplyr's mutate and lag with magrittr to flexibly add lags to a data.frame
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
# | |
# Example of dplyr's mutate and lag with magrittr's %>% | |
# to flexibly add lags to a data.frame | |
# | |
library(dplyr) | |
library(magrittr) # >= v.1.0.1 | |
# A function to generate a mutate call | |
lag_gen <- function(x, lags) | |
{ | |
x <- substitute(x) | |
(function(l) substitute(lag(x, l), list(x = x, l = l))) %>% | |
lapply(X = lags) %>% | |
set_names(paste0(x, ".", lags)) %>% | |
append(quote(mutate), after = 0) %>% | |
as.call | |
} | |
# A test data set. | |
test_data <- | |
data.frame( | |
id = rep(1:10, each = 8), | |
t = rep(1:8, 10), | |
value = runif(80) | |
) | |
# Try it out. Remember to put lag_gen in | |
# parens as it is the resulting call we use. | |
test_data %>% | |
group_by(id) %>% | |
(lag_gen(value, c(1, 2, 7))) %>% | |
head(16) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment