lag_group: Lag a variable by group

Description Usage Arguments Examples

Description

Take the lag of a variable for each group. Will check also that there are no missing years.

Usage

1
2
3
4
5
6
7
8
9
lag_group(
  df,
  group_var,
  value_var,
  time_var,
  lagamount = 1,
  complete_time = seq(min(df[[time_var]]), max(df[[time_var]]), by = 1L),
  default = NA
)

Arguments

df

data frame

group_var

The grouping variable

value_var

The variable to lag over

time_var

The time variable. This is necessary as the function makes sure there are no missing years.

lagamount

The amount of lag

complete_time

Sequence to use for 'completing' df, making sure implicit NAs are turned into explicit ones.

default

Default value for missing? NA by default.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
df_test <- data.frame(group = rep(c("a", "b"), each=6),
                      year = rep(2000:2005, 2),
                      value = (0:11) ^ 2,
                      value2 = rnorm(12))
lag_group(df_test, "group", time_var="year", value_var="value", lagamount = -1:2)

## Behaviour with missing years
lag_group(df_test[-4,], "group", time_var="year", value_var="value", lagamount = -1:2)

## Many lags and many variables:

lag_group(df_test[-4,], "group", time_var="year", lagamount = 1:2, value_var = c("value", "value2"))

MatthieuStigler/multiDiff documentation built on Aug. 10, 2021, 9:42 p.m.