Create a lag

Description

Lag variables by an arbitrary number of periods even if the data is grouped

Usage

1
lag_data(df, group, time, periods, values)

Arguments

df

A dataframe with groups, time periods, and a variable to be lagged

group

The grouping factor in the dataframe

time

The variable representing time periods

periods

A scalar for the number of periods to be lagged in the data. Can be negative to indicate leading variable.

values

The names of the variables to be lagged

Value

A dataframe with a newly created variable lagged

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
test_data <- expand.grid(id = sample(letters, 10), 
                        time = 1:10)
test_data$value1 <- rnorm(100)
test_data$value2 <- runif(100)
test_data$value3 <- rpois(100, 4)
group <- "id"
time <- "time"
values <- c("value1", "value2")
vars <- c(group, time, values)
periods <- 2
newdat <- lag_data(test_data, group="id", time="time", 
                 values=c("value1", "value2"), periods=3)

Want to suggest features or report bugs for rdrr.io? Use the GitHub issue tracker.