Skip to content

Instantly share code, notes, and snippets.

Created May 18, 2014 09:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/0c69b019d0b4f6ae5050 to your computer and use it in GitHub Desktop.
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
#
# 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